原生js事件 mousedown,mouseup,mousemove结合实现元素拖拽

拖拽要注意

解决鼠标焦点丢失问题

鼠标移动过快,会导致鼠标移出盒子,出现盒子和鼠标不同步,且在盒子外鼠标抬起,发现鼠标再次划入盒子,不点击鼠标盒子也仍然还会拖拽。

  1. IE/火狐 把盒子和鼠标绑在一起 调用元素的 setCapture()方法绑定 releaseCapture() 解绑
  2. 谷歌 鼠标不管移动多快 都跑不出浏览器 所以 mousemove/mouseup 绑定给 window

核心代码

<!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>Document</title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    body {
      position: relative;
      height: 10000px;
    }

    #box {
      position: fixed;
      left: 200px;
      top: 200px;
      width: 100px;
      height: 100px;
      background-color: aqua;
    }
  </style>
</head>

<body>
  <div id="box"></div>
  <script>
    // 解决鼠标焦点丢失问题
    // IE/火狐 把盒子和鼠标绑在一起 调用元素的 setCapture()方法绑定 releaseCapture() 解绑
    // 谷歌 鼠标不管移动多快 都跑不出浏览器 所以 mousemove/mouseup 绑定给 window
    const box = document.querySelector("#box");
    // 获取屏幕宽度
    const HTML = document.documentElement;
    // 最大的 left 和 top
    const maxLeft = HTML.clientWidth - box.offsetWidth;
    const maxTop = HTML.clientHeight - box.offsetHeight;
    // TODO 鼠标按下事件 且不能抬起 才能开始移动 鼠标抬起 停止拖拽
    const down = function down(event) {
      // 获取开始盒子的位置
      const { left, top } = this.getBoundingClientRect();
      // 将需要的数据挂载到对象上
      // 盒子起始的位置
      this.startLeft = left;
      this.startTop = top;
      // 鼠标在盒子上点击时的起始位置
      this.startX = event.clientX;
      this.startY = event.clientY;
      // 鼠标按下 绑定鼠标移动事件
      this._MOVE = move.bind(this)
      this._UP = up.bind(this)
      window.addEventListener("mousemove", this._MOVE);
      window.addEventListener("mouseup", this._UP);
    }
    // 鼠标移动 拖拽盒子事件
    const move = function (event) {
      // 获取盒子当前的 left top
      let curLeft = event.clientX - this.startX + this.startLeft;
      let curTop = event.clientY - this.startY + this.startTop;
      // 边界判断 不能超出当前屏幕
      curLeft = curLeft < 0 ? 0 : curLeft > maxLeft ? maxLeft : curLeft;
      curTop = curTop < 0 ? 0 : curTop > maxTop ? maxTop : curTop;
      // 更新盒子的位置
      this.style.left = curLeft + "px";
      this.style.top = curTop + "px";
    }
    const up = function (event) {
      // 鼠标抬起 取消鼠标移动事件绑定
      window.removeEventListener("mousemove", this._MOVE);
      window.removeEventListener("mouseup", this._UP);
    }
    box.addEventListener("mousedown", down);
  </script>
</body>

</html>

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

尤雨东

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值