I can get a style of an element just doing this:
alert (document.defaultView.getComputedStyle (document.getElementById ("element"), null).getPropertyValue ("background-color"));
I can get all styles of an element just doing this:
var styles = document.defaultView.getComputedStyle (document.getElementById ("element"), null);
var string = ""
for (var i = 0; i < styles.length; i ++) {
string = string + styles[i] + ": " + styles.getPropertyValue (styles[i]) + "\n";
}
alert (string);
But, how can I get only the specified styles of an element?
What do you mean by 'specified styles'? Do you mean:
var el = document.getElementById("element");
alert(el.style.display);
alert(el.style.background);
...etc...
or do you mean something like this:
function in_array (needle, haystack, argStrict) {
var key = '', strict = !!argStrict;
if (strict) {
for (key in haystack) {
if (haystack[key] === needle) {
return true;
}
}
} else {
for (key in haystack) {
if (haystack[key] == needle) {
return true;
}
}
}
return false;
}
var styles = document.defaultView.getComputedStyle (document.getElementById ("element"), null);
var string = "";
var whichStyles = ['display','background-color'];
for (var i = 0; i < styles.length; i ++) {
if(in_array(styles[i], whichStyles) {
string = string + styles[i] + ": " + styles.getPropertyValue (styles[i]) + "\n";
}
}
alert (string);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.