禁用移动端滑动手势

使用 CSS 禁止移动端页面的左右划动手势

问题

如何使用 CSS 禁止移动端页面的左右划动手势?

解答

方法一:使用 touch-action

touch-action 属性用于设置触摸屏用户如何操纵元素的区域,可以控制浏览器内置的缩放、滑动等功能。

html {
  touch-action: none; /* 禁用所有手势 */
}

如果只想禁用左右滑动,保留上下滚动:

html {
  touch-action: pan-y; /* 只允许垂直滑动 */
}

方法二:限制宽度和溢出

通过设置元素宽度和隐藏横向溢出内容来防止左右滑动:

html {
  width: 100vw;
  overflow-x: hidden;
}

关键点

  • touch-action: none 禁用所有触摸手势
  • touch-action: pan-y 只允许垂直方向滑动,禁用左右滑动
  • overflow-x: hidden 配合 width: 100vw 可以隐藏横向溢出内容
  • 根据实际需求选择方法,touch-action 更精确,overflow 方案兼容性更好