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方法就用,沒有就用另一個
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM