es6实现drag类

es6 class的使用

之前在Jquery时代,实现拖拽功能都是使用函数直接搞,有了es6中的class,可以很好的封装相关的功能,只要给个ID就可以,想拖谁就拖谁!不过步骤还是老一套。

  1. 先在拖拽元素DOM上添加onmousedown事件,获取鼠标点击位置,并添加document的onmousemove事件和onmouseup事件
  2. 只要鼠标不弹起,就会执行onmousemove事件,然后事件中给拖拽元素top,left赋值,不想让他出去可以,限制范围
  3. 鼠标弹起时,移除事件
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>test</title>
  <style>
    .box {
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
      top: 0;
      left: 0;
    }
  </style>
</head>
<body>

<div class="box" id="box"></div>
<script type="text/javascript">
  
  class Drag {
    constructor(id) {
      this.oDiv = document.querySelector(id);
      this.disX = 0;
      this.disY = 0;
      this.init();
    }

    init() {
      this.oDiv.onmousedown = function (e) {
        //阻止内容被选中
        e.preventDefault();
        this.disX = e.clientX - this.oDiv.offsetLeft;
        this.disY = e.clientY - this.oDiv.offsetTop;
        document.onmousemove = this.fnMove.bind(this);
        document.onmouseup = this.fnUp.bind(this);
      }.bind(this);
    }
    //确保范围不会超出
    ensureRange(e){
      let left = e.clientX - this.disX;
      let width = window.innerWidth - this.oDiv.offsetWidth;
      if (left < 0) {
        left = 0;
      } else if (left > width) {
        left = width;
      }
      let top = e.clientY - this.disY;
      let height = window.innerHeight - this.oDiv.offsetHeight;
      if (top < 0) {
        top = 0;
      } else if (top > height) {
        top = height;
      }
      return {
        top,
        left
      }
    }

    fnMove(e) {
      let xy = this.ensureRange(e);
      this.oDiv.style.left = xy.left + "px";
      this.oDiv.style.top = xy.top + "px";
    }
    //弹起清除
    fnUp() {
      document.onmousemove = null;
      document.onmouseup = null;
    }
  }
  new Drag("#box");
</script>
</body>
</html>


有想换工作的同学可以找我内推哦不低于15k(前端,java,测试)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值