隐藏元素时IE8错误渲染错误的任何解决方案?

时间:2010-06-08 08:38:32

标签: css internet-explorer internet-explorer-8

错误:在IE8中使用JavaScript隐藏元素时,页面上仍然可见的其他元素的边距将被忽略。

IE8引入了这个错误,因为它在IE6 + 7(和其他浏览器)中按预期工作。

<html>
<head>
    <style>
        #a, #b, #c, #d {background: #ccf; padding: 4px; margin-bottom: 8px;}
    </style>
</head>
<body>
    <div id="a">a</div>
    <div id="b">b</div>
    <div id="c">c</div>
    <div id="d">d</div>
    <script>
        setTimeout(function () {
            document.getElementById("b").style.display = "none";
        }, 1000);
    </script>
</body>
</html>

运行此代码时,请注意普通浏览器中ac之间的边距为8,但IE8中的边距为0。

  • 删除填充,IE8的行为与正常情况相同。
  • 删除超时,IE8的行为与正常情况相同。
  • 边框的行为方式相同。

过去10年我一直在使用IE-bugs,但这让我很难过。现在的解决方案是包装div,并将边距应用于外部元素,将其他样式应用于内部。但这让人想起可怕的IE6解决方案。

有更好的解决方案吗?

编辑:我向IE9团队提交了一张票,现在该错误已在IE9中修复。希望他们也会将它向后移植到IE8。

2 个答案:

答案 0 :(得分:1)

这个让我难以接受真正的修复。对于hacky解决方法,您可以将marginBottom重置为8px。显然,设置display:none是删除边距。要验证,请尝试:

    setTimeout(function () {
        document.getElementById("b").style.display = "none";
        document.getElementById("a").style.marginBottom="8px";
    }, 1000);

答案 1 :(得分:0)

edl解决方案的增强功能可以是自动选择并应用前一个元素的margin-bottom。这样您就不必选择(并记住)元素ID和分配的边距。

setTimeout(function () { 
    var e = document.getElementById("b");
    e.style.display = "none";

    var prevSibling = e.previousSibling;
    prevSibling.style.marginBottom = prevSibling.currentStyle.marginBottom;
}, 1000); 

您可能需要检查前一个元素是否存在/是否是错误的一部分。