注入的链接样式表优先于IE7 +中的现有样式 [英] Injected link stylesheet takes precedence over existing styles in IE7+

查看:128
本文介绍了注入的链接样式表优先于IE7 +中的现有样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在级联动态样式表时,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>注入的'test.css'包含 #test {background:green}注册的'test.css'包含
$ b < c。



即使我们将< link> $ c>< style> 标记,IE7 +将覆盖注入的样式表的样式,并应用绿色作为背景。



FF / Chrome这样做正确的方式,让样式标签优先于注入的链接标签,因此背景保持红色。

解决方案

我认为原因是IE定义insertBefore的方式。在IE中,你只能将一个参数传递给insertBefore方法,它的行为与appendChild相同。我想他们做的是插入它然后移动它。



我可以想到的唯一的工作如下(这是不理想的):

/ p>

  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);


There seems to be a bug in IE when cascading dynamic stylesheets. Does anyone know if there is a workaround? Consider this:

<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>

The injected 'test.css' contains #test{background:green}.

Even though we place the <link> before the <style> tag, IE7+ will override the styles with the injected stylesheet and apply green as background.

FF/Chrome do this the right way and lets the style tag take precedence over the injected link tag so the background stays red.

解决方案

I think the cause for this is the way IE defines insertBefore. In IE only you may pass only one parameter into the insertBefore method and it will behave the same as appendChild. I think what they do is insert it THEN move it. If they render at the point of insertion then it would be rendering properly.

The only work around I can think of is as follows (which isn't ideal):

    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);

这篇关于注入的链接样式表优先于IE7 +中的现有样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆