js動態創建style節點(js文件中添加css)


 

ie6 不能 document.createElement('style') 然后append到head標簽里。所以就找到這樣個好文章

---------------------

有很多提供動態創建 style 節點的方法,但是大多數都僅限於外部的 css 文件。如何能使用程序生成的字符串動態創建 style 節點,我搞了2個小時。

靜態外部 css 文件語法:

@import url(style.css);

動態外部 css 文件加載的方法有如下:

第一種:

var style = document.createElement(’link’);
style.href = ’style.css’;
style.rel = ’stylesheet’;
style.type = ‘text/css’;
document.getElementsByTagName(’HEAD’).item(0).appendChild(style);

第二種簡單:

document.createStyleSheet(style.css);

動態的 style 節點,使用程序生成的字符串:

var style = document.createElement(’style’);
style.type = ‘text/css’;
style.innerHTML=”body{ background-color:blue; }”;
document.getElementsByTagName(’HEAD’).item(0).appendChild(style);

很遺憾,上面的代碼在 ff 里面成功,但是 ie 不支持。從老外論壇得到代碼:

var sheet = document.createStyleSheet();
sheet.addRule(’body’,'background-color:red’);

成功,但是很麻煩,要把字符串拆開寫,長一點的寫死,累的像狗一樣。

接着搜,在一個不知道什么國家的什么語言的blog上找到代碼:

document.createStyleSheet(”javascript:’body{background-color:blue;’”);

成功,此人實在厲害,但是問題出來了,url 最大 255 個字符,長一點的就不行了,改:

window.style=”body{background-color:blue;”;
document.createStyleSheet(”javascript:style”);

完美解決!!代碼:

<html> 
<head> 
<script> 
function blue(){ 
if(document.all){ 
window.style="body{"; 
document.createStyleSheet("javascript:style"); 
}else{ 
var style = document.createElement('style'); 
style.type = 'text/css'; 
style.innerHTML="body{ background-color:blue }"; 
document.getElementsByTagName('HEAD').item(0).appendChild(style); 


</script> 
</head> 
<body> 
<input type="button" value="blue" onclick="blue();"/> 
</body>

 

原文  http://www.cnblogs.com/stephenykk/archive/2013/06/10/3131231.html


免責聲明!

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



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