3

我正在帮助调试一个 CSS 问题,其中两个相同的选择器在两个相同配置的服务器之间以不同的顺序加载。一条规则从页面中定义的样式表加载,另一条规则通过注入样式表文件的 Javascript 加载。

根据级联规则,当我阅读它们时,它应该归结为指定规则的顺序。问题似乎是一个竞争条件,但不清楚竞争条件的基础是什么。在 Chrome 的网络选项卡中,文件在两台服务器之间以相同的顺序列出;但是,当您深入到元素选项卡中的元素级别时,将首先列出在给定服务器上优先的规则。

当像这样加载时,是什么决定了 CSS 在两个元素之间“指定”的顺序?

4

2 回答 2

2

如果选择器相同,则归结为 CSS 和DOM中的 order... order 。那么,问题是,您将动态生成的<link>(或<style>)相对于原始<link>(或<style>)放置在哪里?DOM 中的顺序很重要。

如果您想确保首先评估您的动态创建的 CSS,请将其添加到<head>:

document.head.insertBefore(myLink, document.head.firstChild);

如果您希望最后对其进行评估,请将其附加到<body>

document.body.appendChild(myLink);

最后评估的规则将是应用的规则(除非使用!important

这是一个例子:

<!DOCTYPE html>
<html>
  <head>
    <style>
      p {
        color: green;
      }
    </style>
  </head>
  <body>
    <p>test</p>  
    <script>
      (function() {

        var red = document.createElement("style");
        red.textContent = "p { color: red }";
        // We'll add this to the top of head. You'll never even notice because it will
        // be overridden by the existing green style.
        document.head.insertBefore(red, document.head.firstChild);

        var blue = document.createElement("style");
        blue.textContent = "p { color: blue }";
        // We'll add this to the end of the body after a three second delay. It will 
        // override the other styles.
        setTimeout(function() {
          document.body.appendChild(blue);
        }, 3000);

      })();
    </script>
  </body>
</html>

于 2015-04-22T20:43:54.497 回答
2

首先是选择器强度。

如果我使用模式,它是:
inline > identifier (100) > class (10) > tag (1)- 您可以计算括号中的“点”来查找选择器强度。

你知道的,大概。

现在,当您有两个相同强度的选择器时,它们将应用于一个元素,例如。

#main p {color: red}
#top p {color: green}

和 HTML

<div id=main>
    <div id=top>
        <p></p>
    </div>
</div>

段落将为绿色,在开发工具中,红色将被删除。两个选择器具有相同的强度,最新的胜利。

另一个例子是:

#main #top p {color: red} /* will be red, stronger selector */
#main p {color: green}

在 HTML 中,主要因素是样式链接到文档的顺序和规则的顺序(直接在 HTML 或 CSS 中)。首先加载哪个 CSS 文件无关紧要(例如,由于文件大小),HTML 文档中的位置很重要。

于 2015-04-22T20:40:05.417 回答