用JS中document.styleSheets控制cssRules規則

    學習《javascript高級程序設計》的時候知道了一個小小的知識點……以前用JS控制寫在html標籤裏用style屬性的樣式<h1 style="width:100px;">,可以用普通的DOM方法獲得。例如theEl.style.width,但是如果是寫在style標籤下的樣式<type="text/css">h1{width:100px;}</style>,這種方法就會輸出空值。
    這個時候必須用到cssRules集合才能取得、修改該樣式的值。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>css rules</title>
<style type="text/css">
#div1{width:100%;height:400px; background:red;}
</style>
<script>

    window.οnlοad=init;
    function $(id){
              return "string" == typeof id ? document.getElementById(id) : id;
    }
    function init(){
        var ocssRules=document.styleSheets[0].cssRules || document.styleSheets[0].rules || window.CSSRule.STYLE_RULE;
        var theEl=$("div1");
        ocssRules[0].style.background="yellow";
        alert(ocssRules[0].style.background);
    }
    

</script>
</head>

<body>
<div id="div1"></div>
</body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章