react项目实现拖拽

react项目实现拖拽

第一版直接拖拽div不会触发onMouseUp方法,从而导致鼠标松开后div仍会跟着鼠标移动,而且拖动过程中也伴随禁止图标。
因为拖动会触发H5原生的拖拽事件,不会监听到onmouseup。
试了很多方法终于解决了以上问题,贴上优化后的源码供参考

//constructor内
  constructor(props) {
    super(props);
    this.loadedSDK = false;
    this.moving = false;
    this.lastX = null;
    this.lastY = null;
    window.onmouseup = e => this.onMouseUp(e);
    window.onmousemove = e => this.onMouseMove(e);

  }
//方法
  onMouseDown=(e)=> {
    e.preventDefault();//解决了拖动时会出现禁止标志
    e.stopPropagation();
    this.moving = true;
  }

  onMouseUp=(e)=> {
    e.preventDefault();//解决了拖动时会出现禁止标志
    this.moving = false;
    this.lastX = null;
    this.lastY = null;
  }

  onMouseMove=(e)=> {
    e.stopPropagation();
    this.moving && this.onMove(e);
  }

  onMove=(e)=> {
    if(this.lastX && this.lastY) {
    //计算边缘限制x与y的最大值,并限制,默认在最右下角位置(0,0)。
      const selfWidth=this.containerLegend.clientWidth;
      const selfHeight=this.containerLegend.clientHeight;
      const limitWidth=this.container.clientWidth-selfWidth-15;
      const limitHeight=this.container.clientHeight-selfHeight-25;
      const finalX=-1*this.state.translateX>limitWidth?-1*limitWidth:this.state.translateX;
      const finalY=-1*this.state.translateY>limitHeight?-1*limitHeight:this.state.translateY;
      let dx = e.clientX - this.lastX;
      let dy = e.clientY - this.lastY;
      this.setState({ translateX: (finalX + dx)>0?0:finalX + dx, translateY: (finalY + dy)>0?0:finalY + dy })
    }
    this.lastX = e.clientX;
    this.lastY = e.clientY;
  }
//render里

<div id="legend"
      ref={r => {this.containerLegend = r;}}
      onMouseDown={e => this.onMouseDown(e)}
      style={{transform: `translateX(${this.state.translateX}px)translateY(${this.state.translateY}px)`}}></div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值