有很多提供動(dòng)態(tài)創(chuàng)建 style 節(jié)點(diǎn)的方法,但是大多數(shù)都僅限于外部的 css 文件。如何能使用程序生成的字符串動(dòng)態(tài)創(chuàng)建 style 節(jié)點(diǎn),我搞了2個(gè)小時(shí)。
靜態(tài)外部 css 文件語法:
@import url(style.css);
動(dòng)態(tài)外部 css 文件加載的方法有如下:
第一種:
var style = document.createelement(’link’);
style.href = ’style.css’;
style.rel = ’stylesheet’;
style.type = ‘text/css’;
document.getelementsbytagname(’head’).item(0).appendchild(style);
第二種簡(jiǎn)單:
document.createstylesheet(style.css);
動(dòng)態(tài)的 style 節(jié)點(diǎn),使用程序生成的字符串:
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’);
成功,但是很麻煩,要把字符串拆開寫,長(zhǎng)一點(diǎn)的寫死。
接著搜,在一個(gè)不知道什么國(guó)家的什么語言的 blog 上找到代碼:
document.createstylesheet(”javascript:’body{background-color:blue;’”);
成功,此人實(shí)在厲害,但是問題出來了,url 最大 255 個(gè)字符,長(zhǎng)一點(diǎn)的就不行了,經(jīng)過 sxpcrazy 提示,改成:
window.style=”body{background-color:blue;”;
document.createstylesheet(”javascript:style”);
完美解決!!代碼:
<html>
<head>
<script>
function blue(){
if(document.all){
window.style="body{background-color:blue;";
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>
</html>
新聞熱點(diǎn)
疑難解答
圖片精選