You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多页面共用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 07:27:23