拖拽功能有三个事件:
鼠标按下mousedown ,鼠标移动mousemove,鼠标弹起 mouseup
拖拽时,在鼠标移动过程中,获得最新的值赋值给div的left和top值,这样div就可以跟着鼠标走了。
鼠标的坐标减去鼠标在div内的坐标就是div的真正位置。
以下是代码实现:
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 200px;
height: 200px;
background-color: brown;
border: 5px solid black;
position: absolute;
display: block;
cursor: move;
}
</style>
<div class="box" id="box"></div>
<script>
var drag = document.getElementById('box'); // 获取元素
drag.onmousedown = function(e) {
var dragX = e.clientX - drag.offsetLeft;
var dragY = e.clientY - drag.offsetTop;
document.onmousemove = function (e) {
var left = e.clientX - dragX;
var top = e.clientY - dragY;
if (left < 0) {
left = 0;
} else if (left > window.innerWidth - drag.offsetWidth) {
left = window.innerWidth - drag.offsetWidth;
}
if (top < 0) {
top = 0
} else if (top > window.innerHeight - drag.offsetHeight) {
top = window.innerHeight - drag.offsetHeight;
}
drag.style.top = top + 'px';
drag.style.left = left + 'px';
}
document.onmouseup = function (e) {
this.onmouseup = null;
this.onmousemove = null;
}
}
</script>
这样就实现了一个拖拽功能了。