如何使用JavaScript在给定的页面上找到所有的背景图片?
理想的结果是获得一个包含所有URL的数组。
如何使用JavaScript在给定的页面上找到所有的背景图片?
理想的结果是获得一个包含所有URL的数组。
//alert(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;
}
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) ) );
}
}
});
tag.style.backgroundImage
中找到它的,但其他方面都运行得很好。 - lapo以下是一种在页面样式中检查背景URL的方法(不需要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();
获取URL数组。
我在代码中添加了一些(多余的?)注释,解释了它的工作原理。
它不会抓取内联样式,但我认为这对您来说不是问题?
外部样式表和页面上的<style>
标签中的样式被收集。
如果您想保留计数或保留与实际规则相关的关联,则可以轻松修改该例程。
styleSheets
有一些棘手,因为您需要手动检查媒体查询,并在从其他服务器加载CSS文件(例如Google地图样式)时处理CORS限制。 - Philippdocument.querySelectorAll('[style*="background"]')
这是一个复杂的问题。原因是可以使用单独的CSS文件将background-image应用于元素。这样,解析DOM中的所有对象并检查它们的background-image是行不通的。
我能想到的一种方法是创建一个简单的HttpHandler,该处理程序将适用于所有类型的图像。当图像在CSS文件中被引用时,它们会作为单独的实体下载。这意味着HttpHandler将能够捕获图像的类型,然后对其执行。
也许,服务器端的解决方案是解决这个问题的最佳方法!
[...new Set(Array.from(document.querySelectorAll('div')).map(x => window.getComputedStyle(x).getPropertyValue('background-image').split(/[^4],\s*/)).flat())].map(x=>x.replace(/^\s*url\(["']([^"']+)["']\)?\s*$/, '$1'))
function getAllBgInHtml()
{
return document.body.innerHTML.match(/background-image.+?\((.+?)\)/gi).map(function(e){ return ((e.match(/background-image.+?\((.+?)\)/i) || [])[1] || '').replace(/"|"/g,'') });
}
在外部样式表中,不适用于背景图片。