两个盒子,点击鼠标拖拽box1后:box1盒子粘到鼠标上,丢不掉了,这是为什么?
html代码示例:
<body>
<div id="box1">box1</div>
<div id="box2">box2</div>
</body>
css代码示例:
<style type="text/css">
#box1 {
width: 100px;
height: 100px;
background-color: yellowgreen;
position: absolute;
}
#box2 {
width: 100px;
height: 100px;
background-color: orange;
position: absolute;
left: 200px;
top: 200px;
}
</style>
js代码示例:
<script type="text/javascript">
window.onload = function () {
// 拖拽box1元素
/*
拖拽流程
1、当鼠标在被拖拽元素按下时,开始拖拽 onmousedown
2、当鼠标移动时,被拖拽元素跟随鼠标移动 onmousemove
3、当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
*/
// 获取 box1
var box1 = document.getElementById("box1");
// 1、当鼠标在被拖拽元素按下时,开始拖拽 onmousedown
box1.onmousedown = function () {
// 为document 绑定一个onmousemove事件
document.onmousemove = function (event) {
event = event || window.event;
// 2、当鼠标移动时,被拖拽元素跟随鼠标移动 onmousemove
// 获取鼠标的坐标
var left = event.clientX;
var top = event.clientY;
// 修改box1的位置
box1.style.left = left + "px";
box1.style.top = top + "px";
};
// 3、当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
box1.onmouseup = function () {
document.onmousemove = null;
}
};
};
</script>
此时效果为:
点击鼠标拖拽box1后:此时有个小bug , 你点击box1之后,box1盒子粘到鼠标上,丢不掉了!
注意: 此时onmouseup事件绑定给box1,当你往下拖 box1 的时候 ,即box2在上box1在上方的时候,你的鼠标在box2上,触发的是box2的onmouseup。这时有人会说冒泡事件不行吗?此时box1与box2是兄弟事件,只有祖先事件能冒泡!所以事件不能给box1绑定了要给document绑定onmouseup事件!
下面修改下代码:onmouseup事件不能给box1绑定,要给document绑定onmouseup事件!
修改后的代码:之后在运行下操作演示就好了,不会再发生那样的问题了!
<script type="text/javascript">
window.onload = function () {
// 获取 box1
var box1 = document.getElementById("box1");
// 1、当鼠标在被拖拽元素按下时,开始拖拽 onmousedown
box1.onmousedown = function () {
// 为document 绑定一个onmousemove事件
document.onmousemove = function (event) {
event = event || window.event;
// 2、当鼠标移动时,被拖拽元素跟随鼠标移动 onmousemove
// 获取鼠标的坐标
var left = event.clientX;
var top = event.clientY;
// 修改box1的位置
box1.style.left = left + "px";
box1.style.top = top + "px";
};
// 3、当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
document.onmouseup = function () {
document.onmousemove = null;
}
};
};
</script>