多页面共用JS文件时主题切换功能异常问题求助
JavaScript多页面共用脚本问题
原代码文件
index.html
<body> <button class="dark">Dark</button> <p>First Page</p> </body>
second-page.html
<body> <p>Second Page</p> </body>
main.css
root{ --bg-color: white; } .dark{ --bg-color: black; } body{ background-color: var(--bg-color); }
main.js
const btn = document.getElementById('dark') const body = document.body btn.addEventListener('click',function (){ body.classList.toggle('dark') if(body.classList.contains("dark")){ localStorage.setItem("mode","dark") } else{ localStorage.setItem("mode","light") } }); if(localStorage.getItem('mode') == "dark"){ body.classList.toggle('dark') };
问题详情
所有HTML页面都引用同一个JavaScript文件,index.html可正常工作,但second-page.html无法正常运行,原因是该页面没有class为“dark”的按钮。
我尝试了一个解决方案,但逻辑不够合理,且需要在HTML页面中添加更多代码。
我的解决方案是修改变量定义的代码行:
const body = document.body; if (localStorage.getItem('mode') == 'dark') { body.classList.toggle('dark'); } const toggleMode = document.querySelector('.theme-icon'); toggleMode.addEventListener('click', function () { body.classList.toggle('dark'); if (body.classList.contains('dark')) { localStorage.setItem('mode', 'dark'); } else { localStorage.setItem('mode', 'light'); } });
内容的提问来源于stack exchange,提问作者USER2022
相关产品推荐
相关产品推荐

