鼠标事宜
要用鼠标挪动一个div首先要猎取的是鼠标挪动的事宜。
有三个事宜是须要的
- onMouseDown 鼠标按下触发
- onMouseMove 鼠标挪动触发
- onMouseUp 鼠标按钮抬起触发
有了这三个事宜,就能够取得鼠标完全的按下->挪动->抬起完全的操纵
挪动间隔
鼠标onMouseMove事宜会获得许多的间隔
这些都不是须要的,真正须要的间隔是鼠标挪动的间隔dx和dy
那末我们拔取onMouseMove返回的个中的一组clientX和clientY来处置惩罚
- 在class内存储一对变量lastX和lastY
- 第一次鼠标挪动猎取数据后将clientX和clientY放入lastX和lastY
- 第二次鼠标挪动猎取数据后,当前clientX与lastX的差等于dx,clientY与lastY的差是dy
- 而且再将clientX和clientY离别放入lastX和lastY,供下次挪动运用
- 将dx和dy加上本来的坐标举行setState操纵即可挪动div
React完成源码
import React from 'react'
export default class extends React.Component {
constructor(props) {
super(props);
this.state = {
translateX: 0,
translateY: 0,
};
this.moving = false;
this.lastX = null;
this.lastY = null;
window.onmouseup = e => this.onMouseUp(e);
window.onmousemove = e => this.onMouseMove(e);
}
onMouseDown(e) {
e.stopPropagation();
this.moving = true;
}
onMouseUp() {
this.moving = false;
this.lastX = null;
this.lastY = null;
}
onMouseMove(e) {
this.moving && this.onMove(e);
}
onMove(e) {
if(this.lastX && this.lastY) {
let dx = e.clientX - this.lastX;
let dy = e.clientY - this.lastY;
this.setState({ translateX: this.state.translateX + dx, translateY: this.state.translateY + dy })
}
this.lastX = e.clientX;
this.lastY = e.clientY;
}
render() {
return (
<div
onMouseDown={e => this.onMouseDown(e)}
style={{transform: `translateX(${this.state.translateX}px)translateY(${this.state.translateY}px)`}}
>
<div style={{ width: 100, height: 100, backgroundColor: 'blue' }} />
</div>
)
}
};
注
- onMouseDown事宜由div供应,onMouseMove和onMouseUp事宜由window供应的原因是防备鼠标挪动过快形成事宜丧失
- this.moving为纪录挪动最先标志
- stopPropagation作用为停止事宜在流传历程的捕捉、目的处置惩罚或起泡阶段进一步流传
- div的现实挪动由css3属性transform: { translateX, translateY }供应
- 高阶组件封装的github项目链接react-drag-hoc