2016-08-08 30 views
0

問題:如何收集頁面上所有圖像的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. 
    }; 

我不知道如何與圖像信息正確地更新陣列,一旦我有它的所有訪問它它顯示在控制檯日誌。

+0

在'array'中推送'object' – Rayon

回答

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); 
    } 
}); 

而且它會始終顯示圖像的實際數據。

相關問題