当按下“更改”按钮时,样式永远不会返回到声明的 CSS 样式(黑底紫色) - “初始”和“继承”在这里的作用相同...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
section {
color: yellow;
background-color: purple;
}
.demo {
color: purple;
background-color: black;
}
</style>
<button id="change">Change</button>
<section>
<p class="demo">Demo text</p>
<button class="demo">demo button</button>
<input class="demo" type="text" placeholer="demo field" />
</section>
<script>
var flipColors = document.getElementById("change");
var demoFlip = document.getElementsByClassName("demo");
demoFlip.toggleStatus = "onColor";
flipColors.onclick = function() {
switch (demoFlip.toggleStatus) {
case "onColor":
demoFlip.toggleStatus = "flipColor";
for (i = 0; i < demoFlip.length; i++) {
demoFlip[i].style.color = "blue";
demoFlip[i].style.backgroundColor = "yellow";
}
break;
case "flipColor":
demoFlip.toggleStatus = "off";
for (i = 0; i < demoFlip.length; i++) {
demoFlip[i].style.color = "yellow";
demoFlip[i].style.backgroundColor = "blue";
}
break;
case "off":
demoFlip.toggleStatus = "onColor";
for (i = 0; i < demoFlip.length; i++) {
demoFlip[i].style.color = "inherit";
demoFlip[i].style.backgroundColor = "inherit";
}
break;
}
}
</script>
我应该在这里声明颜色吗?我知道这很简单,但我不知道我在这里错过了什么?
最佳答案
“继承”意味着它将采用父级的定义值。在这种情况下,父级是紫色上黄色的。因此,当开关“关闭”时,它会转为继承,因此它会转为部分值。
如果你想使用“继承”并且你想保持该部分的设计原样,你可以将这些东西包装在另一个容器中。
否则,您可以在“off”的情况下定义颜色。
我的做法是为每个版本创建一个 CSS 类并添加/删除它。
功能代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
section {
color: purple;
background-color: black;
}
.demo {
color: purple;
background-color: black;
}
</style>
<button id="change">Change</button>
<section>
<p class="demo">Demo text</p>
<button class="demo">demo button</button>
<input class="demo" type="text" placeholer="demo field" />
</section>
<script>
var flipColors = document.getElementById("change");
var demoFlip = document.getElementsByClassName("demo");
demoFlip.toggleStatus = "onColor";
flipColors.onclick = function() {
switch (demoFlip.toggleStatus) {
case "onColor":
demoFlip.toggleStatus = "flipColor";
for (i = 0; i < demoFlip.length; i++) {
demoFlip[i].style.color = "blue";
demoFlip[i].style.backgroundColor = "yellow";
}
break;
case "flipColor":
demoFlip.toggleStatus = "off";
for (i = 0; i < demoFlip.length; i++) {
demoFlip[i].style.color = "yellow";
demoFlip[i].style.backgroundColor = "blue";
}
break;
case "off":
demoFlip.toggleStatus = "onColor";
for (i = 0; i < demoFlip.length; i++) {
demoFlip[i].style.color = "inherit";
demoFlip[i].style.backgroundColor = "inherit";
}
break;
}
}
</script>
关于javascript - 继承和初始行为相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41379110/