<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#box1{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
}
#box2{
top: 200px;
left: 200px;
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
}
</style>
<script type="text/javascript">
window.onload = function(){
//拖拽box1
//流程:
//1.按住 被拖拽元素开始被拖拽 onmousedown
//2.移动 被拖拽元素随鼠标运动 onmousemove
//3.松开 被拖拽元素固定在当前位置 onmouseup
//获取box1
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
//开启box1的拖拽
drag(box1);
drag(box2);
//提取一个专门用来设置拖拽的函数 //参数:开启拖拽的元素 function drag(obj){ //为obj绑定一个鼠标按下事件 //当鼠标在被拖拽元素上按下时,开始拖拽 onmousedown obj.onmousedown = function(event){ //IE8可以使用“强盗”捕获setCapture()并在鼠标松开事件中取消捕获setCapture() //只有IE支持,但是火狐不报错,而chrome会报错,即需要判断语句判断是否支持setCapture(),支持使用,不支持则不使用 // if(box1.setCapture){ // box1.setCapture(); // } obj.setCapture && obj.setCapture(); event = event || window.event; //div的偏移量 // 鼠标.clientX - 元素.offsetLeft // 鼠标.clientY - 元素.offsetTop var ol = event.clientX - obj.offsetLeft; var ot = event.clientY - obj.offsetTop; }
//为document绑定一个onmousemove事件
document.onmousemove = function(event){
event = event || window.event;
//当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
//获取鼠标的坐标
var left = event.clientX - ol;
var top = event.clientY - ot;
//修改obj的位置
obj.style.left = left+"px";
obj.style.top = top+"px";
};
//当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
//document 是因为 obj 一旦被其他的覆盖就不会被固定
document.onmouseup = function(){
//取消document的onmousemove事件
document.onmousemove = null;
//取消document的onmouseup事件
//因为动作行为结束了留着该事件无意义
document.onmouseup = null;
//IE8可以使用“强盗”捕获setCapture()并在鼠标松开事件中取消捕获setCapture()
obj.releaseCapture && obj.releaseCapture();
}
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
```
```