JavaScript 实现简洁高效的拖拽功能示例

作者:木棉时间:2026-10-21 18:43:02浏览:400

本文分享了一段使用 JavaScript 实现的简洁且高效的拖拽功能代码。通过监听鼠标按下、移动和释放事件,结合兼容性处理,实现了元素的自由拖动。代码结构清晰,适合前端开发者参考学习,可直接集成到项目中以提升交互体验。

JavaScript 拖拽功能实现

本文详细介绍了一个使用 JavaScript 编写的简洁且高效的拖拽功能实现方案。

运行效果如下图所示:

JavaScript 拖拽功能实现

具体实现代码如下:


<!DOCTYPE HTML>
<html>
<head>
 <meta http-equiv="content-type" charset="utf-8" />
  <meta http-equiv="content-type" content="text/html" />
  <title>demo</title>
</head>
<body>
<p>aaaaaaaaaaa</p>
<div id="one" style="height:100px;width:100px;background:red;position:absolute;"></div>
<script>
var odiv=document.getElementById("one");
dra(odiv);
function dra(obj){
  obj.onmousedown=function(e){
    var oe=e||window.event;
    var $this=this;
    var l=oe.clientX-$this.offsetLeft;
    var t=oe.clientY-$this.offsetTop;
    document.onmousemove=function(e){
      var oe=e||window.event;
      var ol=oe.clientX-l;
      var ot=oe.clientY-t;
      if(ol<0) ol=0;
      if(ot<0) ot=0;
      if(ot>document.documentElement.clientHeight-$this.offsetHeight) ot=document.documentElement.clientHeight-$this.offsetHeight;
      if(ol>document.documentElement.clientWidth-$this.offsetWidth) ol=document.documentElement.clientWidth-$this.offsetWidth;
      $this.style.left=ol+"px";
      $this.style.top=ot+"px";
    }
    document.onmouseup=function(){
      document.onmousemove=null;
      document.onmouseup=null;
      if($this.releaseCapture) $this.releaseCapture();
    }
    if($this.setCapture){
      $this.setCapture();
    }
    if(oe.preventDefault) oe.preventDefault();
    else oe.returnValue=false;
    return false;
  }
}
</script>
</body>
</html>

如果您对 JavaScript 的其他技巧感兴趣,可以进一步阅读本站的相关专题,包括《JavaScript 切换特效与技巧总结》、《JavaScript 动画特效与技巧汇总》、《JavaScript 查找算法技巧总结》、《JavaScript 数据结构与算法技巧总结》、《JavaScript 遍历算法与技巧总结》、《JavaScript 中 json 操作技巧总结》、《JavaScript 错误与调试技巧总结》以及《JavaScript 数学运算用法总结》。

希望本文提供的代码示例能对您的 JavaScript 编程工作有所帮助。

作者最新文章