Skip to content

Tailwind CSS - 触摸动作

touch-action 功能类用于控制触摸屏用户如何操作元素的区域(例如,进行平移或缩放)。它们对于创建流畅、可预测的移动和触摸体验至关重要,尤其是在图片轮播、地图或绘图画布等组件中。

这些类映射到 touch-action CSS 属性,使你能够微调浏览器默认的触摸行为。

类名CSS 属性对触摸交互的影响
touch-autotouch-action: auto;浏览器对平移和缩放的默认处理。
touch-nonetouch-action: none;禁用所有平移和缩放。当你需要自定义基于 JavaScript 的触摸处理时非常有用。
touch-pan-xtouch-action: pan-x;启用单指水平平移。禁用垂直平移和缩放。
touch-pan-ytouch-action: pan-y;启用单指垂直平移。禁用水平平移和缩放。
touch-pan-lefttouch-action: pan-left;仅启用向左平移。
touch-pan-righttouch-action: pan-right;仅启用向右平移。
touch-pan-uptouch-action: pan-up;仅启用向上平移。
touch-pan-downtouch-action: pan-down;仅启用向下平移。
touch-pinch-zoomtouch-action: pinch-zoom;启用多指捏合缩放。可能也支持平移。
touch-manipulationtouch-action: manipulation;平移和捏合缩放的有用组合,但会禁用双击缩放。适用于大多数交互式小部件。

在典型的图片轮播中,你希望用户能够上下滚动页面(pan-y),但当他们在轮播图上水平滑动时,你希望移动图片(pan-x),而不是滚动页面。touch-action 属性使这成为可能。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Touch Action for Carousels</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="p-8 font-sans">
<h1 class="text-3xl font-bold mb-4">我的图片画廊</h1>
<p class="mb-6 text-gray-700">你可以正常地上下滚动此页面。在触摸设备上,尝试水平滑动图片画廊。页面不会滚动,但画廊会滚动。</p>
<!-- The container allows horizontal scrolling and sets the touch action -->
<div class="flex space-x-4 overflow-x-auto pb-4 touch-pan-x">
<!-- Image items -->
<div class="flex-shrink-0 w-80">
<img src="https://images.unsplash.com/photo-1682687220247-9f786e34d472?w=500" class="w-full h-48 object-cover rounded-lg shadow-lg" alt="沙漠景观">
<p class="mt-2 font-semibold">沙漠景色</p>
</div>
<div class="flex-shrink-0 w-80">
<img src="https://images.unsplash.com/photo-1707343843982-f8275f3994c5?w=500" class="w-full h-48 object-cover rounded-lg shadow-lg" alt="水下场景">
<p class="mt-2 font-semibold">水下生物</p>
</div>
<div class="flex-shrink-0 w-80">
<img src="https://images.unsplash.com/photo-1709289299190-833b3557a552?w=500" class="w-full h-48 object-cover rounded-lg shadow-lg" alt="建筑细节">
<p class="mt-2 font-semibold">现代建筑</p>
</div>
<div class="flex-shrink-0 w-80">
<img src="https://images.unsplash.com/photo-1709418353393-92f69845d048?w=500" class="w-full h-48 object-cover rounded-lg shadow-lg" alt="船上的人">
<p class="mt-2 font-semibold">乘船游览</p>
</div>
</div>
<div class="mt-8 h-96 bg-gray-200 rounded-lg flex items-center justify-center">
<p class="text-gray-500">下方有更多内容,允许页面滚动。</p>
</div>
</body>
</html>

touch-none 功能类对于绘图画布或自定义地图界面等元素特别有用,因为你在这些场景下使用 JavaScript 处理所有触摸事件。这可以防止浏览器在用户绘图时尝试滚动或缩放页面。

<!-- 在触摸设备上,在此画布上滑动不会滚动页面 -->
<canvas id="drawing-canvas" class="touch-none w-full h-64 bg-white border"></canvas>
  • 为自定义小部件使用 touch-manipulation:对于滑块或自定义按钮等组件,touch-manipulation 通常是最佳选择。它通过启用平移和缩放提供响应式体验,但会禁用与双击缩放相关的 click 事件上的轻微延迟。
  • 防止滚动链效应:在溢出元素上正确设置 touch-action 可以防止“滚动链效应”,即在元素内滚动到达边界后也会导致主页面滚动。这会创建更整洁、更接近原生应用的感觉。
  • 在真机上测试:始终在实际触摸屏设备(手机、平板电脑)上测试你的触摸交互,以确保行为直观且性能良好。