元素拖拽分成3个步骤:按下鼠标,移动鼠标,松开鼠标。
拖拽原理:按下拖拽元素后开始监听文档中鼠标移动事件,然后再监听鼠标松开事件;鼠标移动时,元素div要随着鼠标一起移动,需要计算元素div位移的距离(移动的距离=鼠标离可视窗口的位置 – 鼠标在div中相对于左上角的位置)。然后松开鼠标时,删除移动事件和松开事件,元素完成拖拽
代码参考
<!DOCTYPE html>
<html lang="en">
<title>拖拽</title>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#dog {
width: 150px;
height: 150px;
background: red;
position: fixed;
}
</style>
</head>
<body>
<div id="dog"></div>
</body>
</html>
<script>
utils = {
dragMov:function(dom){
dom.style.cursor = 'move';
dom.onmousedown = function (ev) {
var oEvent = ev || event;
var gapX = oEvent.clientX - dom.offsetLeft;
var gapY = oEvent.clientY - dom.offsetTop;
document.onmousemove = function (ev) {
var oEvent = ev || event;
//限制在可视区域内运动
var l = oEvent.clientX - gapX;
var t = oEvent.clientY - gapY;
var r = document.documentElement.clientWidth - dom.offsetWidth;
var b = document.documentElement.clientHeight - dom.offsetHeight;
if (l < 0) {
dom.style.left = 0 + "px";
} else if (l > r) {
dom.style.left = r + "px";
} else {
dom.style.left = l + "px";
}
if (t < 0) {
dom.style.top = 0 + "px";
} else if (t > b) {
dom.style.top = b + "px";
} else {
dom.style.top = t + "px";
}
}
}
dom.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
}
}
utils.dragMov(document.getElementById('dog'));
</script>