<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
<style type="text/css">
#box1 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
#box2 {
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
left: 200px;
top: 200px;
}
</style>
<script type="text/javascript">
window.onload = function() {
/*
* 拖拽box1元素
* - 拖拽的流程
* 1.当鼠标在被拖拽元素上按下时,开始拖拽 onmousedown
* 2.当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
* 3.当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
*/
//获取box1
var box1 = document.getElementById('box1');
//给box1添加拖拽
box1.onmousedown = function(event) {
event = event || window.event;
//当鼠标点击到box1的时候,
//event.clientX/Y是鼠标到页面的距离
//box1.offsetLeft/Height,是盒子到页面的距离
//相减得到鼠标到盒子边距ol/ot
var ol = event.clientX - box1.offsetLeft;
var ot = event.clientY - box1.offsetTop;
//当鼠标移动时被拖拽元素跟随鼠标移动
//因为盒子移动是在页面document里面移动,所以这里是给document添加
document.onmousemove = function(event) {
//解决兼容问题
event = event || window.event;
//获取鼠标移动坐标;指的是鼠标到页面的距离
//把鼠标到页面的距离减了鼠标到盒子边距ol/ot
var left = event.clientX - ol;
var top = event.clientY - ot;
//把鼠标坐标赋值给盒子
box1.style.left = left + 'px'
box1.style.top = top + 'px'
}
// 当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
//鼠标松开,盒子固定在原来位置,可以理解为当我鼠标松开时候onmousemove结束事件
document.onmouseup = function() {
//结束onmousemove指令操作
document.onmousemove = null;
//onmouseup 在结束onmousemove事件后还在,会加大计算量。所以我们在也要结束onmouseup事件
document.onmouseup = null;
}
}
};
</script>