Come leggere lo stile in linea di un elemento?
-
20-08-2019 - |
Domanda
Mi piacerebbe sapere se è possibile determinare quale stile in linea è stato attribuito a un elemento HTML. Non ho bisogno di recuperare il valore, ma piuttosto di rilevare se è stato impostato in linea o meno.
Ad esempio, se l'HTML fosse:
<div id="foo" style="width: 100px; height: 100px; background: green;"></div>
Come posso determinare che larghezza
, height
e background
sono stati esplicitamente dichiarati, in linea?
Per quanto ne so, la soluzione può funzionare in due modi. Posso chiedergli se è impostato un attributo specifico e mi dirà vero o falso, oppure può dirmi tutti gli attributi che sono stati impostati. In questo modo:
var obj = document.getElementById('foo');
obj.hasInlineStyle('width'); //returns true;
obj.hasInlineStyle('border'); //returns false;
//or
obj.getInlineStyles(); //returns array with values:
// 'width' 'height' and 'background'
Non mi interessano gli attributi CSS ereditati tramite dichiarazioni in un foglio di stile, solo stili incorporati. Un'ultima cosa, non ho alcun controllo sul sorgente HTML.
Grazie
Soluzione
Aggiornato per funzionare con IE
Potresti provare qualcosa del genere
function hasInlineStyle(obj, style) {
var attrs = obj.getAttribute('style');
if(attrs === null) return false;
if(typeof attrs == 'object') attrs = attrs.cssText;
var styles = attrs.split(';');
for(var x = 0; x < styles.length; x++) {
var attr = styles[x].split(':')[0].replace(/^\s+|\s+$/g,"").toLowerCase();
if(attr == style) {
return true;
}
}
return false;
}
Quindi se hai un elemento come questo:
<span id='foo' style='color: #000; line-height:20px;'></span>
Che ha anche un foglio di stile come questo:
#foo { background-color: #fff; }
La funzione restituisce ...
var foo = document.getElementById('foo');
alert(hasInlineStyle(foo,'color')); // true
alert(hasInlineStyle(foo,'background-color')); // false
Altri suggerimenti
La proprietà style di un elemento HTML restituisce un oggetto style che elenca tutte le proprietà. Qualsiasi valore che ha un valore (diverso da una stringa nulla o vuota) è stato impostato sull'attributo inline style.
Potresti provare a fare qualcosa del tipo:
var obj = document.getElementById("foo");
var obj_has_background = (obj.style.background != "");
var obj_has_width = (obj.style.width != "");
var obj_has_height = (obj.style.height != "");
Sembra un po 'lungo, ma questa è la soluzione migliore (e la più breve) che potrei trovare.
Stai cercando di verificare se esiste un determinato attributo di stile o desideri semplicemente un elenco dei possibili attributi? Se conosci già l'attributo, puoi semplicemente usare
hasStyle(obj,'width');
function hasStyle(obj, style)
{
switch(style)
case 'width':
return obj.style.width ? true : false;
case 'background':
return obj.style.background ? true : false;
}
Puoi usare la funzione di Paolo per generare una matrice di stili.