【问题标题】:Css class priority when Adding Dynamic Class添加动态类时的css类优先级
【发布时间】:2016-06-10 12:27:43
【问题描述】:

对css中类的优先级感到困惑,我知道最后添加的类具有最高优先级,但在这里 就我而言,我认为我错了,我将类动态添加到 div,但类无法正常工作

<p>Click the button to add the "mystyle" class to DIV.</p>

<script>
    function myFunction() {
    document.getElementById("myDIV").classList.add("mystyle","hello");
}
</script>

<style>
.hello{
background-color: blue;
}
.mystyle {
    background-color: red;
}
</style>

为什么 div 显示红色而不是蓝色?

Working Example

【问题讨论】:

  • 你回答你自己的问题:class added at the **last** has **highest priority** - 你的最后一节课是.myStyle,所以...
  • 我的意思是在使用这样的类名时说&lt;p class="mystyle hello"&gt;@somethinghere
  • 是的,我意识到阅读下面@kevinto 的答案! HTML 中的类声明与它们的重要性无关,或者在添加它们时,它们都是基于 CSS 中的规则而不是 HTML 中的规则进行评估的。
  • 天啊!在 HTML 中,所有类都是相同的 = 它将使用 CSS 来确定更重要的。

标签: javascript html css


【解决方案1】:

由于您的样式声明顺序,您的div 是红色而不是蓝色:

.hello {
  background-color: blue;
}

.mystyle {
  background-color: red;
}

CSS 特性不依赖于你将类应用到元素的顺序,而是依赖于你在样式中声明类的顺序。在这种情况下,您先声明了.hello,然后声明了.mystyle,这意味着.mystyle 与.hello 相比具有更高的特异性,因此您会得到红色背景。

【讨论】:

  • 很好的答案,您意识到 HTML 中定义的类的顺序与它们的重要性无关。我错过了!
  • 很好的答案,这意味着在 HTML 中声明类并不重要吗?你能提供任何关于这一切的链接吗?
  • 没有真正的链接反驳这一点,但首先阅读 CSS 选择器 (developer.mozilla.org/en/docs/Web/Guide/CSS/Getting_started/…),请记住 CSS 是定义布局的文档。原因是它解耦了你的代码——所以如果你想让其他类在未来更加突出,你只需要改变你的 CSS 文件,而不是 JS 如何将它添加到任何地方或 HTML 声明它的地方。跨度>
  • @PardeepJain,请在此处查看此问题的答案:stackoverflow.com/questions/13849655/…,以及答案所指规范的链接:w3.org/TR/REC-CSS1/#cascading-order
  • 好的,非常感谢您提供的答案和信息@kevinto,也感谢您@somethinghere。
【解决方案2】:

这是层次结构的问题:

function myFunction() {
    document.getElementById("myDIV").classList.add("mystyle","hello", "red-background");
}
#myDIV.hello{
background-color: blue;
}
.mystyle {
    background-color: red;
}
.mystyle {
    width: 300px;
    height: 50px;
    background-color: red;
    color: white;
    font-size: 25px;
}
<p>Click the button to add the "mystyle" class to DIV.</p>

<button onclick="myFunction()">Try it</button>

<p><strong>Note:</strong> The classList property is not supported in Internet Explorer 9 and earlier versions.</p>

<div id="myDIV">
I am a DIV element
</div>

【讨论】:

  • 正如@somethinghere 在上面的 cmets The declaration of classes in HTML is unrelated to their importance or when they were added, it's all evaluated based on the rules in CSS, not rules in HTML 所说,为什么你的 div 显示蓝色而不是 res,因为红色是在 css 中的蓝色之后定义的?这是怎么回事?
  • 我做了一个小提琴,在这里你可以找到所有的解释:fiddle.jshell.net/zd8mzxg3/4
【解决方案3】:

因为解释器首先读取 class .hello 然后读取 class .mystyle ... 那个 div 有两个类......当你的类从 .hello 添加 .mystyle 类的优先级时......

<style>
    .mystyle {
       background-color: red;
    }
   .hello{
      background-color: blue;
   }

</style>

here you can see working example

【讨论】:

    猜你喜欢
    • 2010-11-10
    • 1970-01-01
    • 2011-10-27
    • 2016-12-17
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多