移动端图片缩放时页面还在滚动,怎么处理手势冲突?

闲人宏赛 阅读 46

在开发移动端图片缩放功能时遇到个怪问题,用户双指缩放图片的时候,页面本身还在跟着滚动,导致体验特别差。

我用transform: scale()实现缩放,监听了touchstart和touchmove事件,代码大致这样写的:


<div class="image-container" 
    ontouchstart="handleTouchStart(event)"
    ontouchmove="handleTouchMove(event)">
    <img src="photo.jpg" class="zoomable">
</div>

我尝试给容器加了touch-action: none;overflow: hidden,也用了event.preventDefault(),但快速缩放时页面还是偶尔会滚动。有什么可靠的解决办法吗?

我来解答 赞 10 收藏
二维码
手机扫码查看
2 条解答
W″珊珊
省事的话,直接在 touchmove 事件里加上 event.cancelable && event.preventDefault(),确保只在可取消的情况下调用。另外,给容器加个 overscroll-behavior: none; 就能彻底干掉页面滚动的干扰。

代码可以这么写:

function handleTouchMove(event) {
if (event.cancelable) {
event.preventDefault();
}
// 其他缩放逻辑
}


记得在样式里加上这个:

.image-container {
touch-action: none;
overscroll-behavior: none;
}
点赞
2026-02-18 22:07
FSD-依依
handleTouchMove 里加个判断,确保只在缩放时调用 event.preventDefault(),别无脑阻止默认行为。
代码这样改:

let isScaling = false;

function handleTouchStart(event) {
if (event.touches.length === 2) {
isScaling = true;
}
}

function handleTouchMove(event) {
if (isScaling) {
event.preventDefault();
}
}

function handleTouchEnd() {
isScaling = false;
}


再把容器的 touch-action 设成 pinch-zoom,系统会处理剩下的问题。就这样。
点赞 2
2026-02-14 10:01