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>