<分区>
标签 css background
<分区>
我需要能够将 div 的背景颜色设置回其原始状态。我可以将它存储在一个变量中并调用它,但想知道为什么我不能使用“初始”。现在是为了...将 css 属性设置回其初始状态吗?
提前致谢。
testDiv.style.background = "red";
//Shouldn't this turn it back to it's original state of yellow?
testDiv.style.background = "initial";
#testDiv{
background-color: yellow;
width:40px;
height:40px;
}
<div id="testDiv"></div>
最佳答案
如 documenation 中所述:
The initial CSS keyword applies the initial (or default) value of a property to an element. It can be applied to any CSS property.
和
The initial value of a CSS property is its default value, as listed in its definition table.ref
因此,与您想象的不同,initial 会将初始值放在 之前 您设置 background-color
而不是 您 设置的值。
由于 JS 添加内联样式,您可以简单地删除该样式以返回黄色而无需额外的变量,因为您的样式保持定义但只是被覆盖:
testDiv.style.backgroundColor = "red";
//empty the style attribute
testDiv.style="";
/*OR
testDiv.style.backgroundColor="";
*/
#testDiv{
background-color: yellow;
width:40px;
height:40px;
}
<div id="testDiv"></div>
关于css - 初始颜色...它是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51575630/