js如何引入css文件


1、使用document.write方式輸出引入css的link標簽

在調用文件的頂部加入下例代碼

<script>
    document.write('<link rel="stylesheet" href="main.css">');
</script>

2、使用createElement方法動態創建link標簽,來引入css

在將下邊代碼放入Body中

<script>
    new_element = document.createElement('link');
    new_element.setAttribute('rel', 'stylesheet');
    new_element.setAttribute('href', 'main.css');
    document.body.appendChild(new_element);
</script>

我們來分析一下關鍵的幾句代碼:

首先我們利用document.createElement('link')生成了一個link標簽;

然后設置其rel屬性為stylesheet,href為main.css;

最后將這個標簽動態地加入body中。


免責聲明!

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



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