iOS独立模式PWA重复点击时touch事件未触发的解决咨询
解决iOS独立模式PWA中重复点击touch事件失效问题
经证实,使用ontouchstart并非正确解决方案,使用FastClick.js可解决该问题。
问题背景
我在PWA应用中写了一段点击div切换颜色的代码,原本想通过给body添加ontouchstart=""来消除移动端点击事件的300ms延迟,代码如下:
<html> <head> <style> #click { width: 100px; height: 100px; background-color: blue; } #click:active { background-color: red; } </style> </head> <body ontouchstart=""> <div id="click"></div> </body> </html>
这段代码在iOS 16.1.1的Safari浏览器里运行完全正常,但当PWA以独立模式安装后,快速重复点击时touch事件会无法触发——点击间隔过近的话,后续点击不会触发颜色变化,这个问题在iPhone模拟器里也能复现。
解决方案:使用FastClick.js
ontouchstart的方案在iOS PWA独立模式下存在事件触发异常的问题,替换为FastClick.js可以同时解决点击延迟和重复点击失效的问题:
- 引入FastClick.js
可以通过CDN直接引入,也可以下载本地文件引用:
<script src="https://cdn.jsdelivr.net/npm/fastclick@1.0.6/lib/fastclick.min.js"></script>
- 初始化FastClick
在页面DOM加载完成后,给页面元素绑定FastClick:
document.addEventListener('DOMContentLoaded', function() { FastClick.attach(document.body); });
- 移除冗余代码
删掉body标签上的ontouchstart=""属性,FastClick会自动处理点击逻辑。
修改后的完整代码
<html> <head> <style> #click { width: 100px; height: 100px; background-color: blue; } #click:active { background-color: red; } </style> <script src="https://cdn.jsdelivr.net/npm/fastclick@1.0.6/lib/fastclick.min.js"></script> </head> <body> <div id="click"></div> <script> document.addEventListener('DOMContentLoaded', function() { FastClick.attach(document.body); }); </script> </body> </html>
原理说明
FastClick通过拦截原生的touch事件,在检测到有效的触摸结束后立即触发模拟的点击事件,既消除了300ms的点击延迟,也避开了iOS PWA独立模式下原生touch事件的触发异常,能够稳定处理快速重复点击的场景。
内容的提问来源于stack exchange,提问作者Clément Chaine
相关产品推荐
相关产品推荐

