js获取当前有效样式

 
js获取有效样式
 
节点.currentStyle["属性名"]        兼容ie方法(只有ie有效)
getcomputedStyle(节点)["属性名"]                兼容火狐、谷歌(谷歌火狐有效)
 
总结:既封装的函数为
 
    function getStyle(node, styleType){
        return node.currentStyle? node.currentStyle[styleType]: getComputedStyle(node)[styleType];//浏览器中有node.currentStyle方法就用,没有就用另一个
    }
 
通过节点属性只能获取行间样式,但是有些样式是  外联样式和内联样式    这时候怎么获取呢?
 
示例内联css样式:
        <style>
            #div1{height: 200px; font-size: 9pt;">        
    </style>
 
示例html结构:
    <body>
        <div id = 'div1' style = "width: 100px;"></div>
    </body>
 
   问题描述
             /*
                     只能访问行间样式
                 */
                /*alert(oDiv.style.width); // 100px;
                alert(oDiv.style.height); //        弹出的内容为空字符串 空白 (不报错)
 
*/
 
                /*
                    如何获取当前有效样式?
 
                 */
                
                // alert(oDiv.currentStyle["height"]); //IE兼容 ie下结果  200px
                // alert(getComputedStyle(oDiv)["height"]); //火狐 谷歌兼容  火狐谷歌下 结果 200px;
                
 
既然有兼容性问题,那么我们自己封装一个没有兼容性的函数
 
代码示例:
 
 
<head>
    <meta charset="UTF-8">
    <title>获取当前有效样式</title>
    <style>
        #div1 {
            height: 200px;
            background-color: red;
        }

    </style>
    <script>
        window.onload = function (){
            var oDiv = document.getElementById('div1');
            // alert(oDiv.currentStyle['height']);//ie兼容 结果:200px
            //alert(getComputedStyle(oDiv)['height']) // 结果: 200px; 火狐、谷歌下


/*--------封装一个可以获取当前有效样式切不用考虑兼容问题的函数---------*/

        //分析
            //alert(oDiv.currentStyle);//undefined //ie的方法在火狐或谷歌里没有这个方法,系统定义为undefined
            //alert(Boolean(oDiv.currentStyle)); //undefined   强制转换为布尔值为false  谷歌火狐中测试
            //所以可以这样封装一个函数   浏览器兼容写法
            
            function getStyle(node, styleType){
                return node.currentStyle? node.currentStyle[styleType]: getComputedStyle(node)[styleType];
            }
            /*------函数封装完毕--------*/

            /*-------调用测试--------*/

            alert(getStyle(oDiv, 'height'));// 200px
        

        }
    </script>
</head>
<body>
    <div id = "div1" style="width: 100px;">我是div</div>
</body>
 
 
总结:既封装的函数为
 
    function getStyle(node, styleType){
        return node.currentStyle? node.currentStyle[styleType]: getComputedStyle(node)[styleType];//浏览器中有node.currentStyle方法就用,没有就用另一个
    }

猜你喜欢

转载自www.cnblogs.com/taohuaya/p/9579756.html
今日推荐