在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 () {
document[p] = null
}
}
handleStopDrag事件:阻止默认拖动事件,否则handleDrag会有毛病。
handleStopDrag = (e) => {
e.preventDefault()
}
图片滚轮滚动缩放效果
html(jsx)中
<img
onWheel={this.handleZoom} //缩放事件
ref='zoomImg'
/>
handleZoom事件
handleZoom = (e) => {
let { clientWidth, style } = this.refs.zoomImg
if (e.nativeEvent.deltaY <= 0 && clientWidth < 1000) {
style.width = clientWidth + 10 + 'px' //图片宽度每次增加10
style.left = style.left - 1 % +'px' //随你设置
} else if (e.nativeEvent.deltaY > 0) {
if (clientWidth > 400) {
style.width = clientWidth - 10 + 'px' //图片宽度
style.left = style.left + 1 % +'px'
} else {
style.left = 0
}
}
}