簡體   English   中英

如何使用 javascript 從 web 頁面獲取所有圖像 url?

[英]How to get all image urls from a web page using javascript?

有幾種方法可以使用 javascript 加載圖像 src url,例如使用document.images或選擇所有img標簽並獲取 src。

但是我不知道如何在 css 中使用圖像 url。

例如,如果網頁有以下 css 代碼,它會加載bg.png ,但我無法使用我上面提到的方法得到 url 。

.bg {
  background-image: url('bg.png');
}

任何人都知道如何在 css 中使用所有這些 url?

像這樣的東西:

  1. 循環所有樣式表規則
  2. 從樣式表中獲取文檔元素
  3. 找到背景圖片

 var sSheetList = document.styleSheets; for (var sSheet = 0; sSheet < sSheetList.length; sSheet++) { var ruleList = document.styleSheets[sSheet].cssRules; for (var rule = 0; rule < ruleList.length; rule ++) { if (rule.style.cssText.match(/background/)) { var selectorText = ruleList[rule].selectorText ); var img = document.getElementsByClassName(selectorText); var style = img.currentStyle || window.getComputedStyle(img, false); if( style.backgroundImage ) { var bg = style.backgroundImage.slice(4, -1).replace(/"/g, ""); //add to array here or whatever. } } } }

資源時序 API收集關於出站請求的數據,應該保留在 CSS 和內聯 styles 中收集圖像的能力。

尚未對此進行測試,但類似的東西應該可以幫助您入門:

if ( !('performance' in window) ||
                 !('getEntriesByType' in window.performance) ||
                 !(window.performance.getEntriesByType('resource') instanceof Array)
                 ) {
                      alert('unsupported');
         } else {
            window.addEventListener('load', function() {
               var resources = window.performance.getEntriesByType('resource');
               for(var index in resources) {

                  for(var properties in resources[index]) {
                      console.log(properties);
                      console.log(resources[index][properties]);
                  }
                
               }
            });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM