先说单开关
原理简单的不能再简单,设置一个变量,是数字还是字符随你开心,这里我用最简单的true与false,然后获取你要的节点,然后就是条件判断。
上代码
var boon = false;
var bn1 = document.getElementById("bn1")
var div0 = document.getElementById("div0")
// div0.style.backgroundColor = "#278181",这个东西就是你要不要先设置一个颜色,如果外联或者内部有就不用了
bn1.onclick = function(){
//这个是在观察状态,可有可无
console.log(div0,boon);
//这个就必须要有,每次点击要改变一次boon这个变量的状态,由false变为true,由true变为false。
boon = !boon;
//当然这个和boon === true是一个意思,if只执行true就简单写了
if(boon){
div0.style.backgroundColor = "#000"
}else{
div0.style.backgroundColor = "#278181"
};
}
上一波效果图
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
header{
width: 600px;
height: 400px;
background-color: #278181;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<header id="div0">
</header>
<button id="bn1">按钮</button>
<footer></footer>
<script>
var boon = false;
var bn1 = document.getElementById("bn1")
var div0 = document.getElementById("div0")
// div0.style.backgroundColor = "#278181"
bn1.onclick = function(){
console.log(div0,boon);
boon = !boon;
if(boon){
div0.style.backgroundColor = "#000";
}else{
div0.style.backgroundColor = "#278181"
};
}
</script>
</body>
</html>
**小小总结一下:**这个没有什么复杂的,看看都能懂。所有我们衍生一下。这个可以将最后所保留的状态保存上传到你的服务端,以便用户下一次使用时是他最后所使用的状态。至于更多衍生以后再说。 还有一些其他思路我觉得很好,但我不想用,也不想写。
再说单开关多状态
原理是你不能使用俩个状态的东西,比如true和false。所以我觉得来一个数字取模就是很好的选择。
先上代码
var boon = 0;
var bn1 = document.getElementById("bn1")
var div0 = document.getElementById("div0")
bn1.onclick = function(){
//自增,每次点击加1,注意是保存在栈中。
boon++;
//这个是在观察状态,可有可无
console.log(boon);
if(boon%3 === 1){
div0.style.backgroundColor = "#278181"
}if (boon%3 === 2) {
div0.style.backgroundColor = "#111111"
}if(boon%3 === 0){
div0.style.backgroundColor = "#FF00CC"
}
}
效果图
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
header{
width: 600px;
height: 400px;
background-color: #278181;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<header id="div0">
</header>
<button id="bn1">按钮</button>
<footer></footer>
<script>
var boon = 0;
var bn1 = document.getElementById("bn1")
var div0 = document.getElementById("div0")
bn1.onclick = function(){
boon++;
console.log(boon);
if(boon%3 === 1){
div0.style.backgroundColor = "#278181"
}if (boon%3 === 2) {
div0.style.backgroundColor = "#111111"
}if(boon%3 === 0){
div0.style.backgroundColor = "#FF00CC"
}
}
</script>
</body>
</html>
**小小总结一下:**这个是个三个状态,如果是四个,那就4个if,取模也取4。以此类推。当然如果超过四个,这边建议嵌套一个if,会节省很多代码量。我这边尽量用通俗易懂的话来让各位看的不是那么枯燥。
最后:
如果有什么问题或者共同探讨,欢迎留言私信。