注入的链接样式表优先于 IE7+ 中的现有样式

Dav*_*ing 6 javascript css internet-explorer css-cascade

层叠动态样式表时,IE 中似乎存在错误。有谁知道是否有解决方法?考虑一下:

<head>
    <style>#test{background:red;}</style>
</head>
<body>
    <div id="test">test</div>
    <script>
        var link = document.createElement('link');
        var style = document.getElementsByTagName('style')[0];
        link.rel = 'stylesheet';
        link.href = 'test.css';
        style.parentNode.insertBefore(link, style);
    </script>
</body>
Run Code Online (Sandbox Code Playgroud)

注入的“test.css”包含#test{background:green}.

即使我们将 放在标签<link>之前<style>,IE7+ 也会使用注入的样式表覆盖样式并应用绿色作为背景。

FF/Chrome 以正确的方式执行此操作,并让样式标签优先于注入的链接标签,以便背景保持红色。

Mic*_*rks 2

我认为造成这种情况的原因是 IE 定义 insertBefore 的方式。仅在 IE 中,您只能将一个参数传递到 insertBefore 方法中,并且其行为与appendChild 相同。我认为他们所做的就是插入然后移动它。如果它们在插入点渲染,那么它将正确渲染。

我能想到的唯一解决方法如下(这并不理想):

    var link = document.createElement('link');
    var style = document.getElementsByTagName('style')[0];
    var newstyle = style.cloneNode(true);
    link.rel = 'stylesheet';
    link.href = 'test.css';
    style.parentNode.insertBefore(link, style);
    style.replaceNode(newstyle);
Run Code Online (Sandbox Code Playgroud)