【引言】
今天要给图片预览组件加上手机端使用的双指缩放功能,让手机端用户的体验更好,于是先上网搜索了不少双指缩放的方案,找了半天,大体上都是用scale方法,再搭配一些七的八的监听,我直接CV过来试用,效果不是很满意,玩手机这么多年,相信大家都知道双指缩放什么样的效果是最好的,于是基于各位高手的代码,本人做了一些小修改,代码更加简洁,并放弃scale()缩放,不知为何,用了scale(),图片的位置会在缩放的开始发生变化,这显然是不好的!因此我决定不用scale()
<body>
<img id="image" src="travelTips.png" style="max-width:2000px;min-width:200px;left:50%;top:50%;position:absolute;transform:translate(-50%, -50%);">
<script>
let currentDistance = 0
const getDistance = (start, stop) => Math.hypot(stop.x - start.x, stop.y - start.y)
const eleImg = document.querySelector('#image')
eleImg.addEventListener('touchmove', function (event) {
event.stopPropagation()
event.preventDefault()
const touches = event.touches
const events = touches[0]
const events2 = touches[1]
if (events2) resize(eleImg, {x:events.pageX, y:events.pageY}, {x:events2.pageX, y:events2.pageY})
}, {passive:false})
document.addEventListener('touchmove', function (event) {
event.preventDefault()
const touches = event.touches
const events = touches[0]
const events2 = touches[1]
if (events2) resize(eleImg, {x:events.pageX, y:events.pageY}, {x:events2.pageX, y:events2.pageY})
}, {passive:false})
function resize(dom, start, stop){
const currentVal = getDistance(start, stop)
if(currentDistance < currentVal ) {
dom.style.width = dom.offsetWidth * 1.1 + 'px'
}else{
dom.style.width = dom.offsetWidth * 0.9 + 'px'
}
currentDistance = currentVal
}
</script>
</body>
【优势】
1.各位在其他地方找到的代码,肯定还加上了touchstart,touchend,touchcancel事件的监听等等,还有moveable,store什么的变量,但其实,我试了其实加不加都行,只需要在touchmove的时候监听两个移动的手指即可
2.可以在图片区域进行缩放,而不是只有非图片区域才能进行缩放,让缩放功能更加合理
3.放弃scale(),直接更改元素的width,不会出现一缩放图片位置就改变的问题,scale()方法我尝试过修改transform-origin,效果还是一样