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

如何实现点击主题切换按钮时同步更换按钮内的图片?

实现主题切换时同步切换按钮内的太阳/月亮图标

你只需要在现有主题切换逻辑基础上,添加图标切换的代码即可,具体实现如下:

修改后的完整代码

HTML

<p>text</p>
<div class="container">
  <button class="btn_theme" id="btn_theme">
    <img class="theme-icon" src="https://www.svgrepo.com/svg/304624/sun-light-theme" alt="太阳图标" />
  </button>
</div>

CSS

body {
  background-color: white;
  color: black;
  font-family: "Trebuchet MS", Helvetica, sans-serif;
  font-size: 16pt;
  font-weight: normal;
}

body.dark_theme {
  background-color: #2F3136;
  color: white;
  font-size: 16pt;
  font-weight: normal;
  font-family: "Trebuchet MS", Helvetica, sans-serif;
}

.container {
  width: 100px;
  height: 55px;
  background-color: #2F3136;
  color: white;
  text-align: center;
  border-radius: 10px;
  position: absolute;
  display: flex;
  align-items: center;
}

.btn_theme {
  text-align: center;
  width: 90px;
  height: 45px;
  background-color: white;
  margin: 0;
  padding: 0;
  border: 0;
  left: 5px;
  border-radius: 8px;
  position: relative;
  transition: all .15s linear;
  -webkit-transition: all .15s linear;
  -moz-transition: all .15s linear;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn_theme:hover {
  background-color: #2f3647;
  transition: all 0.15s linear;
  -webkit-transition: all 0.15s linear;
  -moz-transition: all 0.15s linear;
}

.theme-icon {
  width: 30px;
  height: 30px;
  object-fit: contain;
}

JavaScript

const btn = document.querySelector('.btn_theme');
const themeIcon = btn.querySelector('.theme-icon');

// 定义图标资源
const sunIcon = 'https://www.svgrepo.com/svg/304624/sun-light-theme';
const moonIcon = 'https://www.svgrepo.com/svg/6390/moon';

btn.addEventListener('click', function() {
  // 切换主题类,返回值表示是否切换到深色主题
  const isDarkTheme = document.body.classList.toggle('dark_theme');
  
  // 根据主题状态切换图标及描述文本
  themeIcon.src = isDarkTheme ? moonIcon : sunIcon;
  themeIcon.alt = isDarkTheme ? '月亮图标' : '太阳图标';
});

核心优化点

  • 利用classList.toggle()的返回值直接判断主题状态,逻辑简洁高效
  • 给按钮添加flex布局,确保图标在按钮内居中显示
  • 同步更新图标alt属性,提升屏幕阅读器可访问性
  • 固定图标尺寸,避免不同图标大小差异影响视觉一致性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 00:21:43