【问题标题】:How to get all image urls from a web page using javascript?如何使用 javascript 从网页中获取所有图像 url?
【发布时间】:2021-04-26 09:59:55
【问题描述】:

有几种方法可以使用 javascript 加载图像 src url,例如使用 document.images 或选择所有 img 标记并获取 src。

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

例如,如果网页有以下css代码,它会加载bg.png,但我无法使用我上面提到的方法获取该url。

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

有人知道如何在 css 中获取所有这些 url 吗?

【问题讨论】:

  • document.styleSheets在每张表中搜索规则?
  • 使用getComputedStyle。它会帮助你吗? - stackoverflow.com/questions/2104149/…
  • @evolutionxbox 是否可以访问每个单独的样式表规则?
  • @emil,但是您可以使用 forEach() 方法或 for 循环 + 我给您链接的方法遍历所有元素。
  • 另一个想法 - Resource Timing API 收集关于出站请求的数据。也许取决于您的应用程序,您可以使用它来解析出站图像请求?这会抓住一切,不仅是bg图像,还有内联图像。 calendar.perfplanet.com/2012/…

标签: javascript html jquery css dom


【解决方案1】:

Resource Timing API 收集关于出站请求的数据,应该保留以高性能收集 CSS 和内联样式的图像的能力。

尚未对此进行测试,但类似的东西应该可以帮助您入门:

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

【讨论】:

    【解决方案2】:

    类似这样的:

    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.
               }
               }
              
            }
        }

    【讨论】:

    • 感谢您的回答@Squiggs。我认为如果样式表是外部的,您将无法获得规则。
    猜你喜欢
    • 2015-11-27
    • 1970-01-01
    • 2013-08-19
    • 2011-04-18
    • 1970-01-01
    • 2014-01-24
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多