4

我们有一个可以在 IE6 中运行的第 3 方 Web 应用程序,但不能在 IE8 中运行。

示例代码如下所示,“来自 .htc 的消息”消息将在 IE6 中弹出,但在 IE8 中不会弹出。

测试.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<script type='text/javascript'>
    //if comment the following line, or move this script in <body>,
    //then HTC will work in IE8
    document.write ("<h1>document.write() in &lt;head&gt;</h1> some calendar codes");
</script>
</head>

<body style='behavior:url(test.htc)'>
HTML Components test
</body>
</html>

测试.htc

<script type='text/javascript'>
alert ("message from .htc");
</script>

为什么会这样?任何兼容的文件来解释这一点?


解决方案

正如@Quentin 所说或来自http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/c1f546f6-d7e1-4b46-a1c9-8f02eaf1286b的另一位专家所说,IE8 可能与 IE6 相比制定了严格的规则, IE8 可能会将其视为损坏的 HTML 文档。

所以,我决定使用document.createElement动态创建元素,而不是在延迟几秒后将document.write这些元素插入 DOM 。经过一些测试,它终于在这个 test.html 和实际应用程序中都有效。

test-ie8-compatible.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<script type='text/javascript'>
function Delay_CreateCalendar()
{
    var oContainer = document.createElement ("div");
    var oCalendarIFrame = document.createElement ("iframe");
    oContainer.appendChild (oCalendarIFrame);
    document.body.insertBefore (oContainer);
}
setTimeout (Delay_CreateCalendar, 2000);
</script>
</head>

<body style='behavior:url(test.htc)'>
dhtml HTC 测试
</body>
</html>
4

1 回答 1

4

据推测,尽管有命名空间,但您将文档作为 text/html 提供。在 HTML 中,head 和 body 元素的开始和结束标签是可选的。头部内部不允许有 H1 元素。

因此,当您 document.write 和 H1 在结尾时,您会触发头部的结尾和正文的开头。

我假设 IE 然后忽略 body 元素的开始标记,因为它会创建第二个正文(这也是不允许的)。

于 2011-09-29T07:45:38.680 回答