我可以通过以下方式获得元素的样式:
alert (document.defaultView.getComputedStyle (document.getElementById ("element"), null).getPropertyValue ("background-color"));
我可以通过这样做获得元素的所有样式:
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);
但是,我怎样才能获得元素的指定样式?
答案 0 :(得分:0)
'指定样式'是什么意思?你的意思是:
var el = document.getElementById("element");
alert(el.style.display);
alert(el.style.background);
...etc...
或者你的意思是这样的:
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);