Document.write()和document.images[i].宽度在IE8中失败

document.write() and document.images[i].width fails in IE8!

本文关键字:IE8 失败 write images document Document      更新时间:2023-09-26

我使用document.write()只是为了调试一些代码,在IE8中发现了一些非常奇怪的行为。是我错了,还是这是个虫子!

只有4个img元素的页面:

<img src="img/one.jpg" width="100" height="75" alt="1st Demo Image" title="">
<img src="img/two.jpg" width="100" height="75" alt="2nd Demo Image" title="">
<img src="img/three.jpg" width="100" height="75" alt="3rd Demo Image" title="">
<img src="img/four.jpg" width="100" height="75" alt="4th Demo Image" title="">

循环通过document.images HTMLCollection输出每个图像使用document.write()(或document.writeln()没关系)的宽度属性的值:

for (var i=0; i<document.images.length; i++) {
    document.writeln(i + ' - ' + document.images[i]['width']);
}

所有浏览器,除了IE8,输出4行如预期。然而,IE8只输出第一行,用于第一个图像!为什么? !

循环正在'循环' OK。您可以使用alert()输出width属性,并在IE8中得到4个警报,但仍然只有第一行是使用document.write()输出!

for (var i=0; i<document.images.length; i++) {
    document.writeln(i + ' - ' + document.images[i]['width']);
    alert(i + ' - ' + document.images[i]['width']);    // Alerts 4 times
}

'height'属性也是一个问题。然而,其他属性,如'src', 'alt',甚至未定义的属性,如'monkey'输出OK;前提是没有在循环中也有alert() !

如果您将document.write()从循环中取出,在循环中附加一个字符串,并且在循环后只有1个document.write()来输出字符串,那么这是OK的。

这也是一个问题访问宽度属性通过NodeList…document.getElementsByTagName('img')[i].width -和上面一样的问题,只有第一行是输出!

任何想法?或者这只是IE8的怪癖!?

编辑# 1

这段代码是而不是在事件中运行,如onload。它在页面主体的脚本元素中运行,同时对页面进行解析。是的,您不能在事件中调用document.write(),希望影响当前文档,因为文档解析可能已经完成,调用document.write()将隐式打开一个新文档。

这个问题只有在IE8上才会出现。IE6, IE7, IE9和所有其他浏览器测试工作正常

EDIT#2 -找到原因(但不是原因)

好吧,我认为我的测试页面是非常简单的-它似乎是不够简单!我想我已经找到了这个问题的原因(不是原因),但不幸的是,这是它变得更加奇怪的地方!

问题似乎是,如果产生输出的脚本元素直接在元素display:block中。这并不一定是一个本质上是块级元素的元素(如divpre),而是任何属于display:block的元素!块容器和script元素之间不能有空白。

所以,这段代码(在body标签之间)在IE8中再现了这个问题:

<img src="img/one.jpg" width="100" height="75" alt="1st Demo Image">
<img src="img/two.jpg" width="100" height="75" alt="2nd Demo Image">
<img src="img/three.jpg" width="100" height="75" alt="3rd Demo Image">
<img src="img/four.jpg" width="100" height="75" alt="4th Demo Image">
<pre><script type="text/javascript">
// Only the first line is output in IE8, other browsers OK
for (var i=0; i<document.images.length; i++) {
    document.writeln(i + ' - ' + document.images[i]['width']);
}
</script></pre>

但是,如果您在开始的<pre>标记后面只放一个空格,问题就解决了(但是您在输出中得到一个额外的空格)!

而且,这似乎只影响widthheight(数字?)属性!

假定您的document.write清除文档(我不确定这是否取决于每个规范或实现,但这将调用document.open(),这将清除文档包括图像)。因此,在第一次document.write()调用清除文档之后,不再有图像,因此当循环继续访问document.images[1]时,该项目不再可用。

这就解释了为什么任何其他方法都可以工作,因为警告或连接字符串不会清除文档。

如果在文档加载后运行,文档将覆盖正文的内容。

试试这个:

var htm = [];
for (var i=0; i<document.images.length; i++) {
    htm.push(i + ' - ' + document.images[i]['width']); 
}
document.write(htm.join(''));