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


【行間樣式獲取】

<div id='div1' style="backgroud:red">測試</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" class="div2">測試</div>

    <script>

      var odiv=document.getElementById('div1');       //先獲取到要獲取樣式的元素標簽,也就是獲取到div1

      //console.log(getComputedStyle(odiv,null).background);      getComputedStyle("元素","偽類") 是獲取到計算后的樣式,第二個參數是偽類,如果沒有直接使用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" class="div2" >測試</div>

    <script>

      var sheet=document.styleSheets[0]    //獲取到外鏈的樣式表

      var rule=sheet.cssRules[0]        //獲取到外鏈樣式表中的第一個樣式

      console.log(rule.style.background)    //red   這樣就可以獲得了外鏈樣式表中指定的樣式了

    </script>

  </body>

</html>

 

 

【外鏈樣式表】

.div2{

  background:red;

}

 


免責聲明!

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



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