JavaScript獲取css行間樣式,內連樣式和外鏈樣式的簡單方法

字號:


    下面小編就為大家?guī)硪黄狫avaScript獲取css行間樣式,內連樣式和外鏈樣式的簡單方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。
    【行間樣式獲取】
    <div id='div1'>測試</div>   
    <script>
    var odiv=document.getElementById('div1');  //先獲取到要獲取樣式的元素標簽,也就是獲取到div1
    console.log(odiv.style.background);      //這樣我們就可以獲取到了行間的樣式了
    </script>
    【內連樣式獲取】
    <html>
    <head>
     <style>
     .div2{
       background:red;
       }
     </style>
    </head>
    <body>
     <div id="div1">測試</div>
     <script>
     var odiv=document.getElementById('div1');      //先獲取到要獲取樣式的元素標簽,也就是獲取到div1
     //console.log(getComputedStyle(odiv,null).background);   getComputedStyle("元素","偽類") 是獲取到計算后的樣式,第二個參數(shù)是偽類,如果沒有直接使用null  但是萬惡的IE8及之前不支持所以需要用到下面的方法
       //console.log(currentStyle.background)  這個只有IE本身支持 也是獲取到計算后的樣式
    console(window.getComputedStyle?getComputedStyle(odiv,null).background:odiv.currentStyle);      //跨瀏覽器兼容
     </script>
    </body>
    </html>
    【外鏈樣式獲取】
    <html>
    <head>
     <link rel="stylesheet"  type="text/css"  href="basic.css"  />      //外鏈的樣式表
    </head>
    <body>
     <div id="div1" >測試</div>
     <script>
     var sheet=document.styleSheets[0]    //獲取到外鏈的樣式表
     var rule=sheet.cssRules[0]       //獲取到外鏈樣式表中的第一個樣式
     console.log(rule.style.background)    //red  這樣就可以獲得了外鏈樣式表中指定的樣式了
     </script>
    </body>
    </html>
    【外鏈樣式表】
    .div2{
    background:red;
    }
    以上這篇JavaScript獲取css行間樣式,內連樣式和外鏈樣式的簡單方法就是小編分享給大家的全部內容了,希望能給大家一個參考