JS获取级联样式表中的属性值

w3c
window.getComputedStyle(要计算的元素对象,null).marginLeft
document.defaultView.getComputedStyle(要计算的元素对象,null).marginLeft

IE:
id.currentStyle["marginLeft"]
对象.currentStyle["marginLeft"]

访问样式表
+展开
-HTML
<!!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>JS控制样式</title>
<style type="text/css">
/*这个不要去啊。。*/
{
    font-size:12px;
}

</style> 
<script type="text/javascript">
(function () {
    if (window.CSSStyleSheet) {
        var wc = window.CSSStyleSheet.prototype;
        wc.addRule = function (a, b) {
            var wc = this;
            wc.insertRule(a + "{" + b + "}", wc.cssRules.length);
        };
        wc.removeRule = function (a) {
            var wc = this;
            wc.deleteRule(a);
        };
        wc.__defineGetter__("rules"new Function("return this.cssRules"));
    }
})();

var addRule = function (a, b) {
    var wc = document.styleSheets[0], i;
    for (i = 0 ; i < wc.rules.length ; i ++) if (wc.rules[i].selectorText == a) wc.removeRule(i);
    wc.addRule(a, b);
};
var add = function () {
    var wc = document.getElementById("wc").value;
    if (/([^\{]+)\s*(\{[^}]+\})/.test(wc)) {
        addRule(RegExp.$1, RegExp.$2);
    } else {
        alert("样式错误");
    }
};
</script> 
<span class="font">我是字</span><hr >
<button onclick="add()">控制</button>
<textarea style="width:500px;height:500px;" id="wc">
.font {
    font-size:18px;
    font-weight:bold;
    line-height:20px;
    color:#FF0000;
}
</textarea>
</body>
</html> 

加支付宝好友偷能量挖...


评论(0)网络
阅读(159)喜欢(1)JavaScript/Ajax开发技巧