獲取非行間樣式的函數


  1. <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style type="text/css">
                #Div2{width:100px;height:100px; background:black;}
            </style>
            
            <script type="text/javascript">
              window.onload=function(){
                  //獲取行間樣式
                var oDiv=document.getElementById("Div");
                alert(oDiv.style.background);
                
            
                //獲取非行間樣式 ,不可行方案
                var oDiv2=document.getElementById("Div2");
    //            alert(oDiv2.style.background);/用此種方法;是無法獲取非行間樣式的;*
                
                
            //獲取非行間樣式 方法,currentStyle是IE中的屬性,getComputedStyle是其他瀏覽器的方法(注意其有兩個參數);在非行間樣式中,style屬性只能去賦值,在行間樣式中才能去獲取樣式;
            function getStyle(obj, attr)  
            {  
                if(obj.currentStyle)  
                {  
                    return obj.currentStyle[attr];  
                }  
                else  
                {  
                    return  window.getComputedStyle(obj,false)[attr];  
                }  
            }  
            alert(getStyle(oDiv2,"background")) ;  
          }
              
    
            </script>
        </head>
        <body>
        <div id="Div" style="width:100px ;height: 100px; background: red;"></div>
        <div id="Div2"></div>
        </body>
    </html>

     

 

getStyle 函數有 2 個參數,第一個參數 obj 為要獲取的對象,第二個參數 name 為要獲取的屬性,並且做了兼容處理,currentStyle 針對 IE 瀏覽器,getComputedStyle 針對火狐瀏覽器。


免責聲明!

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



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