繁体   English   中英

仅获取元素的指定样式:)

[英]Get only the specified styles of an element :)

我可以通过以下方式获得元素的样式:

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);

但是,如何仅获取元素的指定样式?

“指定样式”是什么意思? 你的意思是:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM