【问题标题】:List of All Background Images in DOMDOM中所有背景图片的列表
【发布时间】:2011-01-26 16:39:33
【问题描述】:

使用 javascript 在给定页面上查找所有背景图像的最佳方法是什么?

理想的最终结果是所有 url 的数组。

【问题讨论】:

  • jQuery 爱好者,请注意标签“无框架”。
  • 主要问题是图像和类可以在 CSS 类中定义。图像将单独下载。但是,您可以创建一个 HttpHandler 来处理所有图像。为此,您需要使用 .NET 框架。
  • 这个问题的答案(第二个 sn-p)是我找到的最快和最短的解决方案:stackoverflow.com/a/4952411/313501

标签: javascript dom css no-framework


【解决方案1】:

这是一个复杂的问题。原因是 background-image 可以通过使用单独的 CSS 文件应用于元素。这种方式解析 DOM 中的所有对象并检查它们的背景图像将不起作用。

我可以看到的一种方法是创建一个简单的 HttpHandler 它将适用于所有类型的图像。在 CSS 文件中引用图像时,它们将作为单独的实体下载。这意味着 HttpHandler 将能够捕获图像的类型,然后在其上执行。

也许服务器端解决方案是最好的解决方案!

【讨论】:

  • OP 请求访问背景图像的方式,而不是常规图像。
【解决方案2】:

其中一种方法是查看所有文档对象并获取样式。然后测试“url(”字符串上的style.background属性,如果匹配,则获取“url(”和“)”之间的路径并将其放入数组。JS的算法。尝试自己做。会发现麻烦 - 附带代码。

【讨论】:

  • 但是如果样式是在 .css 文件中定义的,它可能不起作用。
  • 会的。试试看嘛。无论它们在哪里声明
【解决方案3】:

不使用jQuery,你可以这样做:

var elementNames = ["div", "body", "td"] // Put all the tags you want bg images for here
var allBackgroundURLs = new Array();
elementNames.forEach( function(tagName) {
     var tags = document.getElementsByTagName(tagName);
     var numTags = tags.length;
     for (var i = 0; i < numTags; i++) {
         tag = tags[i];
         if (tag.style.background.match("url")) {
             var bg = tag.style.background;
             allBackgroundURLs.push(bg.substr(bg.indexOf("url") + 4, bg.lastIndexOf(")") - (bg.indexOf("url") + 4) ) );
         }
     }
});

【讨论】:

  • 在 Chrome 中我实际上在 tag.style.backgroundImage 中找到了它,但在其他方面就像一个魅力。
【解决方案4】:

//警报(getallBgimages())

function getallBgimages(){
 var url, B= [], A= document.getElementsByTagName('*');
 A= B.slice.call(A, 0, A.length);
 while(A.length){
  url= document.deepCss(A.shift(),'background-image');
  if(url) url=/url\(['"]?([^")]+)/.exec(url) || [];
  url= url[1];
  if(url && B.indexOf(url)== -1) B[B.length]= url;
 }
 return B;
}

document.deepCss= function(who, css){
 if(!who || !who.style) return '';
 var sty= css.replace(/\-([a-z])/g, function(a, b){
  return b.toUpperCase();
 });
 if(who.currentStyle){
  return who.style[sty] || who.currentStyle[sty] || '';
 }
 var dv= document.defaultView || window;
 return who.style[sty] || 
 dv.getComputedStyle(who,"").getPropertyValue(css) || '';
}

Array.prototype.indexOf= Array.prototype.indexOf || 
 function(what, index){
 index= index || 0;
 var L= this.length;
 while(index< L){
  if(this[index]=== what) return index;
  ++index;
 }
 return -1;
}

【讨论】:

  • 第 6 行不应该是 [^")'] 而不是 [^")] 以便匹配以单引号结尾的网址吗?
【解决方案5】:

这是一种检查页面样式中有哪些背景 url 的方法(看 Ma,没有 jQuery):

window.npup = (function (doc) {
  var sheets = doc.styleSheets;
  var hash = {}, sheet, rules, rule, url, match;
  // loop the stylesheets
  for (var sheetIdx=0, sheetsLen=sheets.length; sheetIdx<sheetsLen; ++sheetIdx) {
    sheet = sheets[sheetIdx];
    // ie or w3c stylee rules property?
    rules = sheet.rules ? sheet.rules : sheet.cssRules;
    // loop the rules
    for (var ruleIdx=0, rulesLen=rules.length; ruleIdx<rulesLen; ++ruleIdx) {
      rule = rules[ruleIdx];
      if (rule.selectorText && rule.style.cssText) {
        // check if there's a style setting we're interested in..
        if (rule.style.cssText.match(/background/)) {
          // ..and if it has an url in it, put it in the hash
          match = /url\(([^)]*)\)/.exec(rule.style.cssText);
          if (match) {hash[match[1]] = true;}
        }
      }
    }
  }
  // return an array of unique urls
  var urls = [];
  for (url in hash) {urls.push(url);}
  // export a getter for what we found
  return {
    getBackgroundUrls: function () { return urls;}
  };
})(document); // submit reference to the document of interest

通过页面上的这个,您可以获得带有npup.getBackgroundUrls(); 的网址数组 我在代码中做了一些(多余的?)注释来解释它是如何进行的。 它不包含内联样式,但我认为这对您来说没问题? 外部工作表和页面上&lt;style&gt; 标记中的样式清除。

如果您想保持计数或保持与找到 url 的实际规则的关联等,该例程很容易修改。

【讨论】:

  • 这对我来说非常有用。对于预加载附加到尚未在 DOM 中的元素的图像特别有用。感谢发帖!
  • 更新了这段代码以获得更好的跨浏览器支持,因此除非首先调用它,否则它不会触发:gist.github.com/1293825 需要注意的重要一点是,此方法可能不适用于不同域上的样式表和端口比当前页面。
  • 我进一步改进了这个函数的版本,以更好地处理 IE 7 和 8。他们将 CSS 属性转换为大写,这个函数没有进行不区分大小写的搜索。更新版本在同一个 URL:gist.github.com/1293825
  • 使用 styleSheets 有点棘手,因为您需要手动检查 媒体查询 并且还需要处理 CSS 文件时的 CORS 限制从其他服务器加载(如谷歌地图样式)
【解决方案6】:

我需要这个功能,但不幸的是它们都太重了。所以考虑一下,这是我的解决方案,如果它可以帮助的话。

function getAllBgInHtml()
{
    return document.body.innerHTML.match(/background-image.+?\((.+?)\)/gi).map(function(e){ return ((e.match(/background-image.+?\((.+?)\)/i) || [])[1] || '').replace(/&quot;|"/g,'') });
}

不适用于外部样式表中的背景图片。

【讨论】:

    【解决方案7】:

    获取具有内联背景样式的集合元素

    document.querySelectorAll('[style*="background"]')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多