js学习之实现拖拽效果

JS原生实现拖拽效果

  • HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    html,
    body {
      height: 100%;
      overflow: hidden;
    }
    .box {
      position: absolute;
      top: 100px;
      left: 200px;
      width: 100px;
      height: 100px;
      background: lightskyblue;
      cursor: move;
    }
  </style>
</head>
<body>
  <div class="box"></div>
</body>
</html>
  • JS代码
/* 
 * 拖拽思路:
     鼠标开始位置A
     鼠标当前位置B(鼠标移动过程中随时计算的)
     盒子开始位置C
     盒子当前位置D = (B - A)+ C

 * 拖拽触发的条件:
     1、鼠标按住盒子才开始拖拽,鼠标抬起则结束拖拽
     2、拖拽开始后,鼠标移动盒子才会跟着移动的

  鼠标按住盒子  mousedown
    + 记录C
    + 记录A
  鼠标移动  mousemove
    + 获取B
    + 动态计算出D
    + 修改盒子的样式,从而让盒子跟着移动
  鼠标抬起  mouseup
    + 取消拖拽
*/

// left top absolute 是距离body 的
// getBoundingClientRect clientX/clientY 是距离窗口的
let box = document.querySelector('.box');

// 获取当前屏幕盒子可移动的范围
let screen = document.documentElement,
    boxData = box.getBoundingClientRect(),
    minL = 0,
    minT = 0,
    maxL = screen.clientWidth - boxData.width,
    maxT = screen.clientHeight - boxData.height;

// 注意统一参照物,盒子位置、鼠标位置是距离窗口的,还是距离body的
// 鼠标按下开始拖拽
function down(ev) {
  // 记录鼠标和盒子的当前位置(参照物:窗口)
  // 记录的这些信息需要在其他方法中用(把信息挂载到盒子的自定义属性上,后期其他方法中只要获取到盒子,就可以根据属性来获取对应的值了)
  let {
    top, 
    left
  } = this.getBoundingClientRect();
  // 把盒子起始位置以自定义属性的方式存储在盒子上
  this.boxTop = top;
  this.boxLeft = left;
  // 把鼠标的起始位置也保存下来
  // this.setCapture(); // IE和火狐解决焦点丢失问题方法(对谷歌无用)
  this.mouseX = ev.clientX;
  this.mouseY = ev.clientY;
  
  // 鼠标按下才做事件绑定
  // box.addEventListener('mousemove', move);
  // box.addEventListener('mouseup', up);

  // 利用事件委托解决焦点丢失问题(注意方法中的this指向,同时还要考虑怎么移除)
  this.moveFn = move.bind(this); // bind会改变函数中的this指向,之后返回一个匿名函数
  this.upFn = up.bind(this);
  window.addEventListener('mousemove', this.moveFn);
  window.addEventListener('mouseup', this.upFn);
}
// 鼠标移动拖拽中
function move(ev) {
  let curL = ev.clientX - this.mouseX + this.boxLeft,
      curT = ev.clientY - this.mouseY + this.boxTop;

  // 边界判断
  curL = curL < minL ? minL :(curL > maxL ? maxL: curL);
  curT = curT < minT ? minT :(curT > maxT ? maxT: curT);

  box.style.left = curL + 'px';
  box.style.top = curT + 'px';
}
// 鼠标抬起,拖拽结束
function up(ev) {
  // 移除事件绑定来结束拖拽
  // this.releaseCapture(); // IE和火狐解决焦点丢失问题方法
  // this.removeEventListener('mousemove', move);
  // this.removeEventListener('mouseup', up);

  // 
  window.removeEventListener('mousemove', this.moveFn);
  window.removeEventListener('mouseup', this.upFn);
}
box.addEventListener('mousedown', down);
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值