意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

onmousemove事件如何用于拖拽功能

来源:佚名 编辑:佚名
2024-07-02 14:13:10

可以通过onmousemove事件来实现拖拽功能,具体步骤如下:

  1. 给需要被拖拽的元素绑定onmousedown事件,当鼠标按下时触发一个函数;
  2. 在这个函数中,获取鼠标按下时的位置,同时给document绑定onmousemove和onmouseup事件;
  3. 在onmousemove事件中,计算鼠标移动的距离,并将被拖拽的元素相应地移动;
  4. 在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>


onmousemove事件如何用于拖拽功能

本网站发布或转载的文章均来自网络,其原创性以及文中表达的观点和判断不代表本网站。
上一篇: onmousemove能实现手势跟踪吗 下一篇: borderStyle和CSS3其他属性的组合