2010-03-12 4 views
10

Qual è il modo migliore per trovare tutte le immagini di sfondo su una determinata pagina utilizzando javascript?Elenco di tutte le immagini di sfondo in DOM

Il risultato finale ideale sarebbe un array di tutti gli URL.

+7

appassionati di jQuery, notare il tag 'no-quadro'. –

+0

Il problema principale è che le immagini e le classi possono essere definite all'interno della classe CSS. Le immagini verranno scaricate separatamente. È tuttavia possibile creare un HttpHandler che gestirà tutte le immagini. Per questo è necessario utilizzare il framework .NET. – azamsharp

risposta

0

Questo è un problema complicato. Il motivo è che l'immagine di sfondo può essere applicata all'elemento usando un file CSS separato. In questo modo l'analisi di tutti gli oggetti nel DOM e il controllo della loro immagine di sfondo non funzionerà.

Uno dei modi che posso vedere è creare un HttpHandler semplice che funzioni su tutti i tipi di immagini. Quando le immagini sono referenziate all'interno del file CSS vengono scaricate come entità separata. Ciò significa che HttpHandler sarà in grado di catturare il tipo dell'immagine e quindi eseguirla.

Forse una soluzione lato server è il modo migliore per andare su questo!

+2

OP richiede il modo di accedere a * background * immagini, non regolari. –

1

Uno dei modi è esaminare tutti gli oggetti del documento e ottenere gli stili. Quindi prova l'attributo style.background su "url (" string e se corrisponde, quindi ottieni il percorso tra "url (" e ")" e mettilo nell'array. Algoritmo per JS. Cerca di farlo da solo. . codice

+0

Ma potrebbe non funzionare se gli stili sono definiti nei file .css. – azamsharp

+0

Lo farà. Prova. No mater dove sono dichiarati – Artic

3

Senza usare jQuery, si può fare:

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

In Chrome, in realtà lo trovo in 'tag.style.backgroundImage', ma per il resto funziona come un incantesimo. – lapo

11

// 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; 
} 
+0

Per la sesta riga, non dovrebbe essere [^ ") '] invece di [^")] in modo da poter confrontare gli URL che terminano con una virgoletta singola? –

1

Ecco un modo per verificare ciò sfondo URL ci sono nel stili sulla pagina (guarda Ma, no 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 

Con questo sulla pagina è possibile ottenere una serie di URL con npup.getBackgroundUrls(); ho fatto alcuni (superfluo?) Commentando il codice che spiega come va su. Non afferra gli stili in linea, ma penso che non sia stato un problema per te? Gli stili nei fogli esterni e nei tag <style> nella pagina sono scavenging.

La routine è facile da modificare se si desidera mantenere un conteggio, o di tenere le associazioni per le attuali regole che un URL è stato trovato nel ecc

+1

Questo funziona perfettamente per me. Particolarmente utile per il precaricamento di immagini che sono associate ad elementi che non sono ancora nel DOM. Grazie per la pubblicazione! – donut

+1

Aggiornato questo codice per un migliore supporto cross-browser e in modo che non si attivi a meno che non venga chiamato prima: https://gist.github.com/1293825 Una cosa importante da notare è che questo metodo probabilmente non funzionerà con fogli di stile su diversi domini e porte rispetto alla pagina corrente. – donut

+1

Ho ulteriormente migliorato la mia versione di questa funzione per gestire meglio IE 7 e 8. Converte le proprietà CSS in maiuscolo e questa funzione non stava eseguendo una ricerca senza distinzione tra maiuscole e minuscole. La versione aggiornata è allo stesso URL: https://gist.github.com/1293825 – donut