如何实现按钮点击切换明暗模式时同步切换图片,再次点击恢复初始状态
问题原因
你代码的核心错误是changeImage函数的两个分支都赋值了同一张暗色模式图片,没有写切回亮色图片的逻辑,所以图片不会切换。另外还有两处可以优化修正的细节:
- CSS中
.main类的font-size属性后语法错误,错把冒号写成分号;定义的.body类没有实际绑定到body元素,样式不生效 - 背景切换和图片切换逻辑可以合并,不需要拆分两个函数分别调用
修正后代码
JS代码
function toggleMode() { const element = document.body; const image = document.getElementById('myImage'); // 切换暗色模式类 element.classList.toggle("dark-mode"); // 同步切换图片 const lightImg = "https://drive.google.com/uc?export=view&id=1zv8IxOU6cHccEanlwTnFmx9HWNQR9AA4"; const darkImg = "https://drive.google.com/uc?export=view&id=1H8ZfWPnLQ1dgKIo7geyyzlkAeh_QHrIa"; image.src = element.classList.contains("dark-mode") ? darkImg : lightImg; }
CSS代码
.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; } .dark-mode { background-color: black; color: white; } .dark-mode .title { color: yellow; background-color: navy; } .dark-mode .img { background-color: teal; } .main { text-align: center; font-size: 50px; border-radius: 20px; font-family: arial; color: #00486B; padding: 25px; background-color: white; }
HTML代码
<!doctype html> <html> <head> <title>模式切换</title> </head> <body class="main"> <h1 class="title">TOGGLE DISPLAY</h1> <img src="https://drive.google.com/uc?export=view&id=1zv8IxOU6cHccEanlwTnFmx9HWNQR9AA4" class="img" id="myImage"> <br> <button onclick="toggleMode()" value="Change">CLICK</button> </body> </html>
内容的提问来源于stack exchange,提问作者Mac Lozano
相关产品推荐
相关产品推荐

