Safari浏览器能否降低滚动速度?适配iOS端Capacitor封装PWA场景
实现方案
针对iOS Safari的滚动速度调整可通过以下两种方案实现,可根据业务场景选择:
CSS极简方案(适合不需要强滚动惯性的场景)
iOS Safari默认给设置了overflow: auto/scroll的元素启用了高速原生惯性滚动,通过修改webkit专属属性即可关闭高速滚动效果,滚动速度会和手指触控位移完全对齐,不会出现滑一下滚动距离过长的问题:
/* 你设置了overflow: auto的div对应的选择器 */ .table-scroll-wrapper { overflow: auto; /* 关闭高速惯性滚动 */ -webkit-overflow-scrolling: auto; }
该方案无性能损耗,适配全版本iOS系统,改动成本极低。缺点是滚动时无惯性效果,手指松开后滚动会立刻停止,更适合内容长度中等的表格使用。
JS自定义阻尼方案(适合需要保留滚动惯性的场景)
如果需要保留惯性滚动效果仅降低滚动速度,可以通过JS监听触控事件实现自定义阻尼滚动,自行调整滚动速度和惯性时长:
- 基础HTML结构
<div class="table-scroll-wrapper" id="scrollContainer"> <!-- 你的大表格代码放在此处 --> </div>
- 对应CSS样式
.table-scroll-wrapper { overflow: auto; /* 关闭原生高速惯性滚动,避免和自定义逻辑冲突 */ -webkit-overflow-scrolling: auto; }
- JS逻辑代码
const scrollContainer = document.getElementById('scrollContainer'); let isTouching = false; let startTouchY = 0; let currentScrollTop = 0; let velocity = 0; let lastTimeStamp = 0; // 阻尼系数:数值越小滚动速度越慢,推荐调整范围0.05~0.3 const DAMPING_FACTOR = 0.15; // 惯性衰减系数:数值越小惯性消失越快,推荐调整范围0.9~0.98 const INERTIA_DECAY = 0.95; scrollContainer.addEventListener('touchstart', (e) => { isTouching = true; startTouchY = e.touches[0].clientY; currentScrollTop = scrollContainer.scrollTop; velocity = 0; lastTimeStamp = performance.now(); }, { passive: true }); scrollContainer.addEventListener('touchmove', (e) => { if (!isTouching) return; const deltaY = e.touches[0].clientY - startTouchY; const now = performance.now(); const deltaTime = now - lastTimeStamp; // 计算实时滚动速度 velocity = (-deltaY) / (deltaTime || 16) * 16; scrollContainer.scrollTop = currentScrollTop - deltaY; lastTimeStamp = now; }, { passive: false }); scrollContainer.addEventListener('touchend', () => { isTouching = false; // 执行惯性滚动动画 function runInertia() { if (Math.abs(velocity) < 0.5) return; velocity *= INERTIA_DECAY; scrollContainer.scrollTop += velocity * DAMPING_FACTOR; requestAnimationFrame(runInertia); } requestAnimationFrame(runInertia); });
你可以自行调整DAMPING_FACTOR和INERTIA_DECAY两个参数的数值,直到滚动速度符合预期即可。
内容的提问来源于stack exchange,提问作者Vasiliy Aristov
相关产品推荐
相关产品推荐

