有很多提供動(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 文件語(yǔ)法:
@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’);
成功,但是很麻煩,要把字符串拆開(kāi)寫(xiě),長(zhǎng)一點(diǎn)的寫(xiě)死。
接著搜,在一個(gè)不知道什么國(guó)家的什么語(yǔ)言的 blog 上找到代碼:
document.createStyleSheet(”javascript:’body{background-color:blue;’”);
成功,此人實(shí)在厲害,但是問(wèn)題出來(lái)了,url 最大 255 個(gè)字符,長(zhǎng)一點(diǎn)的就不行了,經(jīng)過(guò) 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)
疑難解答
圖片精選