3

为什么我无法获得任何数字属性?

我的代码如下:

var img = document.getElementsByTagName("img");  
console.log( "\'img[0].namespaceURI\' results in " + img[0].namespaceURI );
console.log( "\'img[0].height\' results in " + img[0].height );
console.log(img);

弦乐工作。但是没有一个数值...

看图片 在此处输入图像描述

4

2 回答 2

1

控制台中 DOM 元素的轮廓反映了当您单击箭头以显示轮廓时它的状态(取决于浏览器的版本,当轮廓打开时 dom 发生变化时,其内容也会更新)。console.log(img);记录对元素的引用 ,而不是您调用时元素的状态console.log(img);

虽然console.logofimg[0].height显示了height在您进行日志记录时图像的值,因为您height直接请求并且因为它是原始的。因此,如果当时未加载图像,则height调用时显示的console.log(img[0].height)0.

您需要等到图像加载后才能获取其计算 值。

console.log/的这种行为对于console.dir所有非基元都是相同的。Object, Array, DOMElements, ... 作为对控制台的引用传递。字符串、数字、布尔值按值传递到控制台输出。

于 2014-01-17T04:30:24.663 回答
0

很可能图像尚未完全加载。使用onload处理程序。

var img = document.getElementsByTagName("img")[0];  
img.onload = function() {
    console.log( "\'img[0].namespaceURI\' results in " + this.namespaceURI );
    console.log( "\'img[0].height\' results in " + this.height );
    console.log(this);
};

如果图像有可能被缓存,那么您可以检查其.complete属性并在需要时手动调用处理程序。

if (img.complete) 
    img.onload();
于 2014-01-17T04:31:37.860 回答