iPhone浏览器及Mac端Safari中JS事件无法触发问题求助
代码在PC、安卓浏览器运行正常,但iPhone浏览器和Mac端Safari完全无效。试过替换touchmove为touchstart、修改/移除{passive: true},甚至精简onLightPress只执行logo.innerHTML="hi",都没用(其他设备依然正常)。变量能正确获取HTML元素(其他浏览器验证过)。
以下是包含暗黑模式功能的示例代码,仅运行该函数也存在相同问题:
document.addEventListener('DOMContentLoaded', function() { //REQUIRED VARIABLES var lightmode = 0; const tiles = document.querySelector('.tiles'); const shuffled = document.querySelector('.shuffled'); const lightbulb = document.querySelector('#lightbulb'); let heading = document.querySelector('.heading'); let logo = document.querySelector('.logo'); let box = document.querySelectorAll('.box'); let hidden = document.querySelectorAll('.hiddenletters'); let body = document.querySelector('.body'); let menu = document.querySelector('.menu'); let revealed = document.querySelector('.revealed'); let toptimes = document.querySelector('.toptimes'); let ranking = document.querySelectorAll('.ranking'); let donate = document.querySelector('.donate'); counttoday.classList.toggle('logodark'); // 此处counttoday未声明 //LIGHTBULB FUNCTIONALITY lightbulb.addEventListener('touchmove', onLightPress, { passive: true }); lightbulb.addEventListener('click', onLightPress, { passive: true }); function onLightPress() { heading.classList.toggle('headingdark'); logo.classList.toggle('logodark'); tiles.classList.toggle('tilesdark'); Array.from(box).forEach((box) => box.classList.toggle('boxdark')); Array.from(shuffled).forEach((shuffled) => shuffled.classList.toggle('shuffleddark')); Array.from(hidden).forEach((hidden) => hidden.classList.toggle('hiddenlettersdark')); body.classList.toggle('bodydark'); menu.classList.toggle('menudark'); revealed.classList.toggle('logodark'); toptimes.classList.toggle('logodark'); counttoday.classList.toggle('logodark'); // 同样未声明 donate.classList.toggle('logodark'); lightmode++; if (lightmode % 2 != 0) { Array.from(ranking).forEach((ranking) => ranking.setAttribute('id', 'darktext')); } else { Array.from(ranking).forEach((ranking) => ranking.removeAttribute('id', 'darktext')); } } })
(原谅我还没搞定ranking的切换逻辑 😂)
问题排查与解决方案
核心问题:未定义变量counttoday
Safari对未声明变量的处理比Chrome等浏览器更严格,代码中直接调用counttoday.classList.toggle('logodark')但未提前声明该变量,会直接抛出ReferenceError,阻断后续所有代码执行(包括事件监听绑定),这是功能完全失效的主要原因。
修复建议
补全变量声明
根据HTML结构添加counttoday的声明:let counttoday = document.querySelector('.counttoday'); // 替换为实际对应的选择器若该变量是冗余代码,直接删除所有涉及
counttoday的代码行即可。简化事件监听
移动端Safari的touchmove触发条件较严格,且click事件在移动端可正常响应,建议先移除touchmove监听,优先保证核心交互:// 移除touchmove监听,click事件无需passive选项 lightbulb.addEventListener('click', onLightPress);优化ranking切换逻辑
避免反复操作ID(ID应唯一,不适合批量元素),改用类名切换更合理:// 替换原if-else逻辑 Array.from(ranking).forEach((item) => item.classList.toggle('darktext'));同时将CSS中
#darktext的样式改为.darktext。修正shuffled选择器
若页面中有多个.shuffled元素,原代码querySelector仅获取第一个,需改为:const shuffled = document.querySelectorAll('.shuffled');
调试技巧
打开Safari开发者工具(Mac端通过「开发」菜单开启;iPhone需连接电脑,在设置中开启「Web检查器」),查看控制台错误信息,可快速定位其他潜在问题。
内容的提问来源于stack exchange,提问作者JG1629Code

