【问题标题】:Initial color... how's it work? [duplicate]初始颜色...它是如何工作的? [复制]
【发布时间】:2019-01-05 14:55:21
【问题描述】:

我需要能够将 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>

【问题讨论】:

    标签: css background


    【解决方案1】:

    documenation中所述:

    初始 CSS 关键字应用 a 的初始(或默认)值 元素的属性。它可以应用于任何 CSS 属性。

    CSS 属性的初始值是它的默认值,如所列 其定义表。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>

    【讨论】:

      【解决方案2】:

      您将initial 设置为元素的style.background 属性的 - 这意味着它将覆盖选择元​​素的CSS 中的默认背景颜色。如果您想将 background 属性重置为 CSS 指定的属性,请改用 removeProperty,以完全删除 Javascript 设置的属性,以便页面的 CSS 重新获得最高优先级:

      testDiv.style.background = "red";
      testDiv.style.removeProperty('background');
      #testDiv{
        background-color: yellow;
        width:40px;
        height:40px;
      }
      <div id="testDiv"></div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-02
        • 1970-01-01
        • 2019-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-22
        相关资源
        最近更新 更多