1.html代码
<div class="card" ref="card" @wheel.prevent="rollImg">
<img ref="imgDiv" @load="toEnd" @mousedown.prevent="drag" @touchstart.prevent="drag" class="cardImg":style="{ left: `${left}px` }" src="url" alt="">
</div>
2.script代码
export default {
name: 'Picture',
data() {
return {
left: '',
canmove: false
}
},
methods:{
// 图片加载完成,让其走到最后
toEnd() {
this.$refs.imgDiv.left = -9999
this.compare()
},
// 拖拽
drag(e) {
let img = this.$refs.imgDiv
this.canmove = true
let move = (e, x) => {
if (!this.canmove) return
this.left = e.pageX - x
this.compare()
}
/* 元素到页面距离 = 鼠标到页面的距离 - 鼠标到元素的距离 */
if (e.type == 'mousedown') {
let x = e.pageX - img.offsetLeft
document.addEventListener('mousemove', e => {
move(e, x)
})
document.addEventListener('mouseup', () => this.canmove = false)
} else {
e = e.targetTouches[0]
let x = e.pageX - img.offsetLeft
document.addEventListener('touchmove', ev => {
move(ev.targetTouches[0], x)
})
document.addEventListener('touchend', () => this.canmove = false)
}
},
// 拖拽计算
compare() {
let img = this.$refs.imgDiv
let card = this.$refs.card
let min = card.offsetWidth - img.width
let max = 0
/* 范围公式 a ∈ [min,max],则 a 和 min 取最大值,和 max 取最小值 */
if (this.left == '') this.left = -9999
this.left = Math.min(Math.max(this.left, min), max)
},
// 鼠标滚轮横向滚动
rollImg(e) {
let step = e.deltaY > 0 ? 50 : -50
this.left += step
this.compare()
},
}
}
3.css代码
.card {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.card .cardImg {
height: 100%;
position: absolute;
top: 0;
right: 0;
cursor: grab;
}
我的图片是进入页面定位在最右边,向左拖拽查看图片