做盒子的拖拽

<!DOCTYPE html>
<html lang="en">
  <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>
    <style>
      .box {
        width: 200px;
        height: 200px;
        background-color: gold;
        position: absolute;
        left: 100px;
        top: 100px;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>
    <script>
      // 拖拽需要有三个事件的支撑
      // 鼠标按下 => mousedown
      // 鼠标移动 => mousemove
      // 鼠标抬起 => mouseup
      let box = document.querySelector('.box');

      // 鼠标按下
      box.onmousedown = function (e) {
        // 每一次按下都需要获取当前的初始位置
        let startX = box.offsetLeft;
        let startY = box.offsetTop;
        // console.log(startX, startY);

        // 获取按下时候的鼠标落点位置
        let x = e.pageX;
        let y = e.pageY;

        // 鼠标移动
        document.onmousemove = function (e) {
          // 使用移动过程的最新鼠标落点 - 按下位置的鼠标落点  = 当前这一次的移动距离
          let dx = startX + e.pageX - x;
          let dy = startY + e.pageY - y;

          if (dx <= 50) {
            dx = 50;
          } else if (dx >= window.innerWidth - box.offsetWidth - 50) {
            dx = window.innerWidth - box.offsetWidth - 50;
          }

          if (dy <= 50) {
            dy = 50;
          } else if (dy >= window.innerHeight - box.offsetHeight - 50) {
            dy = window.innerHeight - box.offsetHeight - 50;
          }

          // 修改box的left和top的取值
          // 最终的位置: 每一次移动前初始位置 + 当前这一次的距离
          box.style.left = dx + 'px';
          box.style.top = dy + 'px';
        };
        // 鼠标抬起
        document.onmouseup = function () {
          // 解绑mousemove事件
          document.onmousemove = null;
        };
      };
    </script>
  </body>
</html>

  • 11
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值