原生js实现拖动效果

以前写过但是太复杂了,这次直接用原生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实现拖动效果

0
  • 本文分类:JavaScript
  • 本文标签:拖拽拖动
  • 流行热度:已超过 67 人围观了本文
  • 发布日期:2020年07月31日 - 10时30分00秒
  • 版权申明:本文系作者@木灵鱼儿原创发布在木灵鱼儿站点。未经许可,禁止转载。

评论(0)

相关文章

微信收款码
微信收款码