1.拖拽的基本效果。
思路:
-
鼠标在盒子上按下时,准备移动 (事件加给物体)
-
鼠标移动时,盒子跟随鼠标移动 (事件添加给页面)
-
鼠标抬起时,盒子停止移动 (事件加给页面)
var o = document.querySelector('div');
//鼠标按下
o.onmousedown = function (e) {
//鼠标相对于盒子的位置
var offsetX = e.clientX - o.offsetLeft;
var offsetY = e.clientY - o.offsetTop;
//鼠标移动
document.onmousemove = function (e) {
o.style.left = e.clientX - offsetX + "px";
o.style.top = e.clientY - offsetY + "px";
}
//鼠标抬起
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
}
2.拖拽的问题。
若盒子中出现了文字,或盒子自身为图片,由于浏览器的默认行为(文字和图片本身就可以拖拽),我们可以设置return false来阻止它的默认行为,但这种拦截默认行为在IE低版本中,不适用,可以使用全局捕获来解决IE的问题。
全局捕获
全局捕获仅适用于IE低版本浏览器。
<button>btn1</button>
<button>btn2</button>
<script>
var bts = document.querySelectorAll('button')
bts[0].onclick = function () {
console.log(1);
}
bts[1].onclick = function () {
console.log(2);
}
// bts[0].setCapture() //添加全局捕获
// bts[0].releaseCapture() ;//释放全局捕获
</script>
一旦为指定节点添加全局捕获,则页面中其它元素就不会触发同类型事件。
3
完整版的拖拽
var o = document.querySelector('div');
//鼠标按下
o.onmousedown = function (e) {
if (o.setCapture) { //IE低版本
o.setCapture()
}
e = e || window.event
//鼠标相对于盒子的位置
var offsetX = e.clientX - o.offsetLeft;
var offsetY = e.clientY - o.offsetTop;
//鼠标移动
document.onmousemove = function (e) {
e = e || window.event
o.style.left = e.clientX - offsetX + "px";
o.style.top = e.clientY - offsetY + "px";
}
//鼠标抬起
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
if (o.releaseCapture) {
o.releaseCapture();//释放全局捕获
}
}
return false;//标准浏览器的默认行为
}