onmousemove事件如何用于拖拽功能
导读:可以通过onmousemove事件来实现拖拽功能,具体步骤如下: 给需要被拖拽的元素绑定onmousedown事件,当鼠标按下时触发一个函数; 在这个函数中,获取鼠标按下时的位置,同时给document绑定onmousemove和onmo...
可以通过onmousemove事件来实现拖拽功能,具体步骤如下:
- 给需要被拖拽的元素绑定onmousedown事件,当鼠标按下时触发一个函数;
- 在这个函数中,获取鼠标按下时的位置,同时给document绑定onmousemove和onmouseup事件;
- 在onmousemove事件中,计算鼠标移动的距离,并将被拖拽的元素相应地移动;
- 在onmouseup事件中,解绑document的onmousemove和onmouseup事件,结束拖拽操作。
示例代码如下:
<
!DOCTYPE html>
<
html>
<
head>
<
style>
#drag {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
<
/style>
<
/head>
<
body>
<
div id="drag" onmousedown="drag(event)">
<
/div>
<
script>
function drag(event) {
var dragElement = document.getElementById("drag");
var startX = event.clientX - dragElement.offsetLeft;
var startY = event.clientY - dragElement.offsetTop;
document.onmousemove = function(event) {
var newX = event.clientX - startX;
var newY = event.clientY - startY;
dragElement.style.left = newX + "px";
dragElement.style.top = newY + "px";
}
;
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
}
;
}
<
/script>
<
/body>
<
/html>
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: onmousemove事件如何用于拖拽功能
本文地址: https://pptw.com/jishu/685748.html