关于javascript:看到一位大哥写的原生拖拽保存一下

40次阅读

共计 1416 个字符,预计需要花费 4 分钟才能阅读完成。

拖拽的实现是通过给元素设置 position 为相对定位,而后在鼠标按下的时候记录下地位,而后监测文档内鼠标的挪动情况,来更改元素款式的 left 和 top 值来实现了拖动的成果。大佬博客指路。代码如下:

<!DOCTYPE html>
<html lang="cn">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title> 拖拽 </title>
</head>
<style>
  .container{
    width: 100%;
    position: relative;
    height: 100%;
  }
  #drag{
    width: 50px;
    height: 50px;
    background-color: red;
    position: absolute;
    cursor: move;
  }
</style>
<body>
  <div class="container">
    <div id="drag"></div>
  </div>

  <script>

    let drag = document.querySelector('#drag')

    drag.onmousedown = function(event){
      // 获取到事件对象
      // 从中能够获取到鼠标所在的地位,计算出 dom 元素的地位
      console.log(event);
      var diffX = event.clientX - drag.offsetLeft;
      var diffY = event.clientY - drag.offsetTop;
      if(typeof drag.setCapture !== 'undefined'){drag.setCapture(); 
      }

      document.onmousemove = function(event){
          var event = event || window.event;
          var moveX = event.clientX - diffX;
          var moveY = event.clientY - diffY;
          if(moveX < 0){moveX = 0}else if(moveX > window.innerWidth - drag.offsetWidth){moveX = window.innerWidth - drag.offsetWidth}
          if(moveY < 0){moveY = 0}else if(moveY > window.innerHeight - drag.offsetHeight){moveY =  window.innerHeight - drag.offsetHeight}
          drag.style.left = moveX + 'px';
          drag.style.top = moveY + 'px'
      }
      document.onmouseup = function(event){
          this.onmousemove = null;
          this.onmouseup = null;
            // 修复低版本 ie bug  
          if(typeof drag.releaseCapture!='undefined'){drag.releaseCapture();  
          }  
      }

    }
  </script>
</body>
</html>

另外博客还介绍了一种 H5 的拖拽,通过给元素设置属性 draggable=”true” 来容许元素拖拽,而后监听元素的拖拽事件,来实现。

正文完
 0