标签:
获取内存中(正在渲染)的 style 的值(非内联 style,obj.style 只能获得内联 style 的值),可以用 obj.currentStyle(低版本 IE 和 Opera 支持)和 window.getComputedStyle(IE9 以及 标准浏览器支持)来获取。
window.getComputedStyle 的格式是 window.getComputedStyle(obj,伪元素)
第一个参数是要要获取计算后的样式的目标元素
第二个参数是期望的伪元素,如"after","first-letter"等,一般为 null
可以封装获取运行时的 style 对象的函数
function getStyle(obj, attr){ return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj, null)[attr]; }
注:这两个方法获取的对象是只读的,要改样式必须使用 obj.style。
【例】
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #div1{
            width: 300px;
            height: 300px;
            background: blue;
            border-bottom: 1px solid black;
        }
    </style>
</head>
<body>
    <div id="div1" onclick="t();"></div>
</body>
<script>
    function getStyle(obj, attr){
        return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj, null)[attr];
    }
    function t(){
        var div = document.getElementById("div1");
        div.style.width = parseInt(getStyle(div, "width")) + 5 + ‘px‘;
        div.style.height = parseInt(getStyle(div, "height")) + 5 + ‘px‘;
        div.style.borderBottomWidth = parseInt(getStyle(div, "borderBottomWidth")) + 1 + ‘px‘;
    }
</script>
</html>      
Javascript 笔记与总结(2-9)获取运行时的 style 对象
标签:
原文地址:http://www.cnblogs.com/dee0912/p/4467647.html