3 回答
TA贡献1111条经验 获得超0个赞
我将为您提供一个带有代码的示例,您可以解决其余的问题。
var colors = ["#2D2D2D"]; // I don’t know why you have an array of
// color, but I could get this to be much simpler without using
// array, but I followed your example to make it simpler for you
var colorIndex = 0;
function changeColor() {
var col = document.getElementById("body");
if (colorIndex >= colors.length) {
colorIndex = 0;
}
if (colors[colorIndex] == col.getAttribute("currentColor")) {
col.style.backgroundColor = null; // Take the CSS color
col.setAttribute("currentColor",col.style.backgroundColor);
}
else {
col.style.backgroundColor = colors[colorIndex];
col.setAttribute("currentColor", colors[colorIndex]);
}
colorIndex++;
}
#body{
background-color: red;
}
<div id="body">
<label class="switch">
<input id="input" onclick="changeColor();" type="checkbox">
<span class="slider round"></span>
</label>
</div>
TA贡献1828条经验 获得超6个赞
试试这些
方法一:
为浅色和深色主题定义单独的样式。根据所需主题在 body 上设置类
JavaScript:
function toggleTheme() {
document.getElementsByTagName('body')[0].classList.toggle('light');
document.getElementsByTagName('body')[0].classList.toggle('dark');
}
CSS:
body.light {
background-color: white;
color: black;
}
body.light button {
background-color: blue;
color: black;
}
body.dark{
background-color: black;
color: white;
}
body.dark button {
background-color: grey;
color: black;
}
方法二:
定义变量属性并在您的应用程序中使用这些属性来设置样式
JavaScript:
Same as above
CSS:
body.light {
--color: black;
--backgroundColor: white;
}
body.dark {
--color: white;
--backgroundColor: black;
}
button {
color: var(--color);
background-color: var(--backgroundColor);
}
TA贡献1802条经验 获得超10个赞
您可以创建一个变量来处理状态,设置布尔初始值并在每次单击切换按钮时更新其值,例如:
let actived = false;
function setState(){
if(actived == false){
changeColor1();
actived = true;
} else {
changeColor2();
actived = false;
}
}
<input type="button" (onclick)="setState()"/>
添加回答
举报