获取图片信息并在页面控制台中显示调整大小

时间:2016-08-08 20:56:37

标签: javascript css image

问题:我如何收集页面上所有图像的src,宽度和高度,然后每当当前页面更改大小时,都会在控制台中显示图像信息。

示例代码:

var images = document.getElementsByTagName('img'); 
var srcList = [];
for(var i = 0; i < images.length; i++) {
    srcList.push(images[i].src);
srcList.push(images[i].width);
srcList.push(images[i].height);
}

window.onresize=function(){
for(var i = 0; i < images.length; i++) {
console.log(srcList[i]);
}
//I am pretty sure I would have to go get the new width and height of the images on the page. Should I just loop through and populate the array like above? The source would stay the same. 
  };

我不确定如何使用图像信息正确更新阵列,一旦我让它全部访问它以在控制台日志中显示它。

1 个答案:

答案 0 :(得分:1)

document.getElementsByTagName会返回与标记名匹配的实时 HTMLCollection元素。 直播表示文档中的任何修改都会反映在集合中。因此,您只需要创建一次集合,并且每次查询时都会有实时数据。

所以你可以这样做:

var images = document.getElementsByTagName('img');
window.addEventListener('resize', function() {
  for(i=0; i<images.length; i++) {
    console.log(images[i].src, images[i].width, images[i].height);
  }
});

它将始终显示图像的实际数据。