以前写过但是太复杂了,这次直接用原生js写了,相对来说简单了很多。

html,
    body {
      margin: 0;
      padding: 0;
    }

    #box {
      position: absolute;
      width: 200px;
      height: 200px;
      border: 2px solid #92cccc;
      background: rgba(0, 0, 0, 0.5);
    }
 <div id='box'></div>
var box = document.getElementById("box");
    var spaceX = null;
    spaceY = null;
    winWidth = null;
    winHeight = null;
    //按下的时候计算好间距
    box.addEventListener("mousedown", function (event) {
      const e = event || window.event;
      e.stopPropagation();
      //计算环境得到数据
      //间距
      spaceX = e.clientX - box.offsetLeft;
      spaceY = e.clientY - box.offsetTop;
      //可视宽高
      winWidth = window.innerWidth
        || document.documentElement.clientWidth
        || document.body.clientWidth;
      winHeight = window.innerHeight
        || document.documentElement.clientHeight
        || document.body.clientHeight;

      //添加事件
      document.addEventListener('mousemove', boxMousemove, false);

    }, false);

    //删除移动事件
    box.addEventListener("mouseup", function () {
      document.removeEventListener('mousemove', boxMousemove, false);
      this.style.cursor = "default";
    });

    //移动事件
    function boxMousemove(event) {
      const e = event || window.event;
      const realX = e.clientX - spaceX;
      const realY = e.clientY - spaceY;
      //x轴移动
      if (realX + box.offsetWidth >= winWidth) {
        box.style.left = winWidth - box.offsetWidth + "px";
      } else if (realX < 0) {
        box.style.left = 0 + "px";
      } else {
        box.style.left = e.clientX - spaceX + "px";
      };
      //y轴移动
      if (realY + box.offsetHeight >= winHeight) {
        box.style.top = winHeight - box.offsetHeight + "px";
      } else if (realY < 0) {
        box.style.top = 0 + "px";
      } else {
        box.style.top = e.clientY - spaceY + "px";
      };

      //鼠标样式
      box.style.cursor = "move";
    }

效果图

原生js实现拖动效果

分类: JavaScript 标签: 拖拽拖动

评论

暂无评论数据

暂无评论数据

目录