鼠标拖拽是一种常见的js效果,下面贴一下原生js的实现方法。
注:第一段段js代码来自网络,第二段是在第一段基础上改进实现的。由于时间太久找不到出处,侵删。
先贴上一张对象和窗口之间距离的示意图方便理解,下文中也有注释。

HTML代码
CSS代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| html,body { height: 100%; }
body { position: relative; overflow: hidden; margin: 0; }
#move { width: 200px; height: 100px; background-color: #ddd; border: 1px solid #000; position: absolute; z-index: 1; }
|
Javascript代码
可以将元素拖拽出窗口外
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
window.onload = function() { var box = document.getElementById("move"); move.onmousedown = function(e) { var e = e || event; console.log(e); var target = e.target || e.srcElement; var disX = e.clientX - target.offsetLeft; var disY = e.clientY - target.offsetTop; document.onmousemove = function(e) { target.style.left = e.clientX - disX + "px"; target.style.top = e.clientY - disY + "px"; } document.onmouseup = function(e) { document.onmousemove = null; document.onmousedown = null; } } }
|
无法将元素拖拽出窗口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| window.onload = function() { var box = document.getElementById("move"); move.onmousedown = function(e) { var e = e || event; var target = e.target || e.srcElement; var disX = e.clientX - target.offsetLeft; var disY = e.clientY - target.offsetTop; document.onmousemove = function(e) { target.style.left = e.clientX - disX + "px"; target.style.top = e.clientY - disY + "px"; if (target.offsetLeft + target.offsetWidth >= document.body.clientWidth) { target.style.left = document.body.clientWidth - target.offsetWidth + "px"; } if (target.offsetLeft < 0) { target.style.left = 0 + "px"; } if (target.offsetTop + target.offsetHeight >= document.body.clientHeight) { target.style.top = document.body.clientHeight - target.offsetHeight + "px"; } if (target.offsetTop < 0) { target.style.top = 0 + "px"; } }; document.onmouseup = function(e) { document.onmousemove = null; document.onmousedown = null; } } }
|