强制IE重新计算样式?

时间:2012-01-16 17:28:06

标签: javascript css internet-explorer

我构建了一个类似于http://code.google.com/p/jingo/的javascript / css依赖管理器。

它允许我做这样的事情:

Loader.DependsOn(['/scripts/jqueryui.js', '/scripts/jquery.js'])
      .Css('/css/jquery.css')
      .Execute(function() { //Insert script here});

Loader将在执行前动态加载脚本和css(如果它们尚未加载)。

一切正常,IE浏览器除外。通过在文档头部附加链接来加载样式表。但是,在执行此操作之前,加载程序会查看请求的css文件本身是否依赖于另一个模块。如果是,它将确定应该插入CSS文件的顺序。在除IE之外的所有浏览器中,如果我将其插入列表的开头,之后的任何其他样式表将覆盖它的样式(预期行为)。然而,在IE中,虽然它在开头插入,但IE将其视为最终。

有没有办法强制IE重新计算样式?

更新测试案例:

创建两个样式表,sheet1.css,sheet2.css

sheet1.css

.testdiv
{
    width:200px;
    height:200px;
    background-color:#c7c7c7;
}

sheet2.css

.testdiv
{
    width:400px;
    height:400px;
}

标记:

<html>
    <head>
        <link href="style1.css" rel="stylesheet" "type="text/css" />
    </head>
    <body>
        <div class="testdiv">
        </div>
    </body>
</html>
<script type="text/javascript" language="javascript>
     setTimeout(function() {

        var link = document.createElement('link');
        link.href = 'sheet2.css';
        link.rel = 'stylesheet';
        link.type = 'text/css';
        var head = document.head || document.getElementsByTagName('head')[0];
        head.insertBefore(link, head.children[0]);

        setTimeout(function () {
            //suggestion from Simon West
            document.body.className = document.body.className;
        }, 3000);

    }, 3000);    
</script>

会发生什么:

灰盒200px×200px。 3秒后,它仍在那里。没有变化。

IE8会发生什么

灰盒200px×200px。 3秒后,它增长到400px 400px。

Safari(Windows)上会发生什么 -

灰盒200px×200px。 3秒后,它仍在那里。没有变化。

无论有没有@Simon West的建议,都会发生这种情况。

2 个答案:

答案 0 :(得分:1)

<html>
<head>
    <link href='sheet1.css' rel='stylesheet' type='text/css'>
</head>
<body>
    <div class='testdiv'></div>
    <script type='text/javascript'>
setTimeout(function() {
    var link = document.createElement('link');
    link.href = 'sheet2.css';
    link.rel = 'stylesheet';
    link.type = 'text/css';
    var head = document.getElementsByTagName('head')[0];
    head.insertBefore(link, head.children[0]);

    var docElem = document.documentElement,
        docElemNext = docElem.nextSibling;
    document.removeChild(docElem); // this will clear document.styleSheets
    document.insertBefore(docElem, docElemNext);
}, 500);
    </script>
</body>
</html>

答案 1 :(得分:0)

以下JS代码段应强制重新整理/重绘整个页面。

document.body.className = document.body.className;