css - 初始颜色...它是如何工作的?

标签 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/

上一篇:html - 位置 : sticky doesn't work when html height: 100%

下一篇:css - 动画文本持续时间

相关文章:

android - 网站在现代 Android 浏览器中以不同方式呈现是否很常见?

html - 带滚动条的背景图片

php - 如何杀死后台php线程?

iphone - 如何为分组 TableView 设置背景图像?

css - div 在响应式背景图片之上

javascript - 如何将悬停规则添加到 css className 以便在悬停时为 react 表中的特定行着色?

css - 使用多个选择器将 CSS 样式应用于元素失败

ios - 重置 box-sizing 对 iOS safari web 有什么危害吗?

Python Tkinter 文本背景

html - 如何选择不是父 div 子级但位于父 div 外部的 div?