在react项目
按住鼠标左键移动图片效果
html(jsx)中
<img
className='zoomImg'
onDragStart={this.handleStopDrag}
onMouseDown={(e) => { e.persist(); this.handleDrag(e) }}
/>
handleDrag事件
handleDrag = (e) => {
const o = $('.zoomImg')[0]
const s = o.style
const p = 'onmousemove'
//在jsx中需要用e.persist()此方法会从池中移除合成事件,允许用户代码保留对事件的引用,否则clientX会是null
let x = e.clientX - o.offsetLeft;
let y = e.clientY - o.offsetTop;
document[p] = function (e) {
s.left = e.clientX - x + 'px';
s.top = e.clientY - y + 'px';
}
this.setState({
event: document[p]
})
document.onmouseup = function () {
documen