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

通过按钮切换网站暗模式时修改图片padding背景色及标题样式问题

问题根因

你仅为<body>元素切换了dark-mode类,但标题、图片的样式为独立固定配置,不会跟随父级类名变化自动适配,且原有dark-mode类优先级低于<body>绑定的.main类,导致文字色修改不生效。

修改方案

  1. 修正CSS语法错误:.main类中font-size后的分隔符误写为分号,调整为冒号
  2. 提升暗模式样式优先级,新增标题、图片的暗模式适配规则
  3. 可选补充按钮暗模式适配,避免样式突兀

修改后完整代码如下:

<!doctype html>
<html>
<head> 
<style> 
.title {
  font-size: 50px; 
  text-align: center; 
  background-color: #C1C1C1; 
  border-radius: 20px; 
  font-family:arial; 
  color: #00486B;
}
.img {
  background: coral; 
  width: 500px; 
  padding: 30px; 
  margin-left: auto; 
  margin-right: auto; 
  display: block;
}
.body {
  padding: 25px; 
  background-color: white; 
  color: black; 
  font-size: 25px;
}
/* 提升暗模式优先级,适配body.main */
body.dark-mode {
  background-color: black; 
  color: white;
}
.main {
  text-align: center; 
  font-size: 50px; 
  border-radius: 20px; 
  font-family: arial; 
  color: #00486B;
}
/* 新增暗模式下标题适配 */
body.dark-mode .title {
  background-color: #2b2b2b;
  color: #99d8ff;
}
/* 新增暗模式下图片padding背景适配 */
body.dark-mode .img {
  background-color: #422a22;
}
/* 可选:暗模式下按钮适配 */
body.dark-mode button {
  background: #333;
  color: #fff;
  border: 1px solid #666;
  padding: 8px 16px;
  border-radius: 4px;
}
</style> 
<script>
function myFunction(){
  var element = document.body;
  element.classList.toggle("dark-mode")
}
function changeImage(){
  var image = document.getElementById('myImage');
  if (image.src.match("skeletons.jpg")) {
    image.src = "joseph.jpg";
  } else {
    image.src= "skeletons.jpg";
  }
} 
</script>
<title>Java</title>
</head> 
<body class="main">
  <h1 class="title">Toggle Display</h1>
  <img src="skeletons.jpg" class="img" id="myImage">
  <br>
  <button onclick="myFunction(); changeImage();" value="Change">CLICK</button>
</body>
</html>

适配参数可根据实际视觉需求自行调整颜色数值。

内容的提问来源于stack exchange,提问作者Mac Lozano

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:06:07