js 拖拽

2020-03-31  本文已影响0人  Do_Du

e.clientX:指鼠标距离浏览器左边的距离
e.clientY:指鼠标距离浏览器上边的距离

div.offsetTop: div元素到距离浏览器可视化窗口上边的距离
div.offsetLeft: div元素到距离浏览器可视化窗口左边的距离

wps2.jpeg wps1.jpeg

如果要设置物体拖拽,那么必须使用三个事件,并且这三个事件的使用顺序不能颠倒。

1、onmousedown:鼠标按下事件

2、onmousemove:鼠标移动事件

3、onmouseup:鼠标抬起事件

注:

1、一定要绝对定位

2、onmousedown绑定拖拽的元素,onmousemove和onmouseup是针对document的绑定,因为移动的是整个div

3、计算

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  #box {
    width: 400px;
    height: 150px;
    background: purple;
    position: absolute;
    cursor:move;
  }
</style>
<body>
  <div id="box"></div>
  <script>
    window.onload = function () {
      var box = document.getElementById('box');

      box.onmousedown = function (e) {
        e = event || window.event;
        var diffX = e.clientX - box.offsetLeft;
        var diffY = e.clientY - box.offsetTop;
        
         //修复低版本ie bug
        if(typeof box.setCapture !== 'undefined'){
          box.setCapture(); 
        }

        document.onmousemove = function (e) {
          e = event || window.event;
          var moveX = event.clientX - diffX;
          var moveY = event.clientY - diffY;

          // 边界判断
          if (moveX < 0) {
            moveX = 0;
          }else if (moveX > window.innerWidth - box.offsetWidth){
            moveX = window.innerWidth - box.offsetWidth;
          }
          if (moveY < 0) {
            moveY = 0;
          }else if (moveY > window.innerHeight - box.offsetHeight) {
            moveY = window.innerHeight - box.offsetHeight;
          }
          // 关键性赋值绝对定位top left距离
          box.style.left = moveX + 'px';
          box.style.top = moveY + 'px';
        }

        // 鼠标抬起,清楚绑定再文档上的mousemove和mouseup事件,否则鼠标抬起后还可以继续拖拽方法  
        document.onmouseup = function (e) {
          e = event || window.event;
          this.onmousemove = null;
          this.onmouseup = null;

           //修复低版本ie bug
          if(typeof box.releaseCapture!='undefined'){  
            box.releaseCapture();  
          }  
        }
      }
    } 
  </script>
</body>
</html>

// 转自:https://blog.csdn.net/weixin_41910848/article/details/82218243

上一篇下一篇

猜你喜欢

热点阅读