原生js实现锁定方向拖拽

实现一个盒子可以上下拖拽、左右拖拽、锁定拖拽的小功能,欢迎指正批评!!!

布局:

 

 

 

 

    拖放状态

 

 

样式:

div,

    html,

    body,

    button,

    p {

      margin: 0;

      padding: 0;

    }

    #hanBall {

      width: 100px;

      height: 100px;

      background: lawngreen;

      position: absolute;

    }

js代码:

  var oHanBall = document.getElementById("hanBall");

  var oHanp = document.getElementsByTagName("p")[0];

  var oHansuo = document.getElementsByTagName("button")[3];

  var oHanchui = document.getElementsByTagName("button")[2];

  var oHanshui = document.getElementsByTagName("button")[1];

  var Shui = (chui = 1);

  var suo = 1;

  // 鼠标按下

  var tz = oHanBall.onmousedown = function () {

    var event = event || window.event;

    // console.log(event)

    var x1 = event.clientX;

    var y1 = event.clientY;

    // console.log(x1)

    var L = oHanBall.offsetLeft;

    var T = oHanBall.offsetTop;

    console.log(L);

    // 鼠标移动

    document.onmousemove = function (event) {

      var x2 = event.clientX;

      var y2 = event.clientY;

      // console.log(x2,y2)

      var x = x2 - x1;

      var y = y2 - y1;

      // console.log(x,y);

      oHanp.innerText =

        `left:` + oHanBall.style.left + `top:` + oHanBall.style.top + ``;

      if (suo == 1) {

        if (Shui == 1) {

          oHanBall.style.left = x + L + "px";

        }

        if (chui == 1) {

          oHanBall.style.top = y + T + "px";

        }

      }

    };

    // 鼠标抬起

    document.onmouseup = function () {

      document.onmousemove = null;

      document.onmouseup = null;

      oHanp.innerText = "拖拽结束";

    };

  };

  // 锁定位置事件

  oHansuo.onclick = function () {

    if (suo == 1) {

      suo = 2;

      this.innerText = "取消锁定位置";

    } else {

      suo = 1;

      this.innerText = "锁定位置";

    }

  };

  // 垂直锁定事件

  oHanchui.onclick = function () {

    if (chui == 1) {

      chui = 2;

      this.innerText = "取消垂直锁定";

    } else {

      chui = 1;

      this.innerText = "垂直锁定";

    }

  };

  // 水平锁定

  oHanshui.onclick = function () {

    if (Shui == 1) {

      Shui = 2;

      this.innerText = "取消水平锁定";

    } else {

      Shui = 1;

      this.innerText = "水平锁定";

    }

  };

你可能感兴趣的:(原生js实现锁定方向拖拽)