js 修改css檔案

來源:互聯網
上載者:User

標籤:nbsp   檔案   char   修改   size   highlight   ref   code   com   

在做自動換膚設定時,無意中看到了js修改css的方法,感覺挺有用的,特來學習分享一下。好了,下面開始學習:js的 document.styleSheets 擷取到的是引入的css的對象數組。如:

其中  CSSStyleSheet展開如下:

document.styleSheets[0] 即可得到你所應用的第一個cssrules 和 cssRules 的計數方法是不一樣的!rules 是第幾個選取器;cssRules 是第幾條規則document.styleSheets[0].cssRules即可得到所有css檔案行document.styleSheets[0].cssRules[0] css第一條document.styleSheets[0].cssRules[0].style.background="red"//修改第一條的背景顏色為紅色

執行個體:

修改標題1的字型顏色為紅色引入的css:
.wode{    color: #000;    font-size: 36px;}.article{    color: #333;}h1,h2,h3{    color: #0D9BF2;}
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <link rel="stylesheet" href="style.css"></head><body><div class="article">    <h1>標題一</h1>    <div class="content">內容</div>    <h2>標題二</h2>    <div class="content">內容</div>    <h3>標題三</h3>    <div class="content">內容</div></div><script>    var cssRule=document.styleSheets[0].cssRules;    console.log(cssRule);    console.log(cssRule.length);    for(var i=0;i<cssRule.length;i++){        if(cssRule[i].selectorText.indexOf("h1") != -1){            cssRule[i].style.color="red";        }    }</script></body></html>

 

修改前:

 

修改後:

 

 

js 修改css檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.