javaScript動態添加樣式


[動態添加css樣式]

<html>

  <head>

    <script type="text/javascript">

      window.onload=function(){

        var head=document.getElementsByTagName('head')[0];     //獲取到head元素 

        var link=document.createElement('link');             //創建link元素節點,也就是link標簽

          link.rel="stylesheet";                    //為link標簽添加rel屬性

          link.href="basic.css";                    //為link標簽添加href屬性 , 屬性值是css外鏈樣式表的路徑

        head.appendChild(link);                    //將link元素節點添加到head元素子節點下

        

 }

    </script>

  </head>

  <body>

    <div id="div1">測試</div>

  </body>

</html>

 

[動態添加script標簽]

原理同上

<html>

  <head>

    <script type="text/javascript">

       window.onload=function(){

        var head=document.getElementsByTagName('head')[0];     //獲取到head元素 

        var script=document.createElement('script');           //創建script標簽

          script.type="text/javascript";                //為script標簽添加type屬性         

          script.src="basic.js";                    //為script標簽添加scr屬性,屬性值為js路徑

        head.appendChild('script');                  //將script標簽添加到head的子節點下

 

}

    </script>

  </head>

  <body>

    <div id="div1">測試</div>

  </body>

</html>

 


免責聲明!

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



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