javascript —訪問外部定義的CSS樣式(類定義的CSS樣式)

來源:互聯網
上載者:User

event3.css

.mydiv{    width:600px;    height:400px;    background-color:red;}

event3.html

<html><head><link rel="stylesheet" type="text/css" href="event3.css"><meta http-equiv="content-type" content="text/html;charset=utf-8"><!--js代碼可以放置在任意位置,按照先後順序依次執行 一般放在head標籤之間--><script type="text/javascript">        function test(){        window.alert(new Date().toLocaleString());    }//    訪問外部定義的CSS樣式(類定義的CSS樣式)    function test2(eventObj){        //擷取event.css中所有class選取器都擷取        //注意:Mozilla和Safasi中是cssRules,而IE中是rules        var ocssRules=document.styleSheets[0].rules;        //從ocssRules中取得你需要的class        var mydiv=ocssRules[0]; //這個0是表示是event3.css檔案中的第一個規則        if(eventObj.value=="黑色"){            //通過Id來區分進行操作            var div1=document.getElementById("div1");            div1.style.backgroundColor="black";        }else if(eventObj.value=="紅色"){            var div1=document.getElementById("div1");            //div1.style.background-color="balck"; //這樣寫是錯的            div1.style.backgroundColor="red";        }    }</script></head><body>    <input type="button" value="點擊顯示時間" onclick="test()" />    <div id="div1" class="mydiv">            </div>    <input type="button" value="黑色" onclick="test2(this)"/>    <input type="button" value="紅色" onclick="test2(this)"/></body></html>

 

相關文章

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.