国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > CSS > 正文

Javascript動(dòng)態(tài)創(chuàng)建 style 節(jié)點(diǎn)

2024-07-11 08:21:14
字體:
供稿:網(wǎng)友

有很多提供動(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>

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 九龙坡区| 夏河县| 德安县| 晋城| 金堂县| 贡觉县| 明光市| 修武县| 巴青县| 万安县| 新郑市| 晋州市| 龙里县| 铜川市| 上高县| 乌拉特中旗| 凌源市| 南宫市| 靖宇县| 禄劝| 武冈市| 九龙坡区| 隆昌县| 泽州县| 辽阳市| 肇源县| 固阳县| 尤溪县| 文昌市| 丰县| 大化| 腾冲县| 方山县| 林西县| 雅安市| 庆云县| 康平县| 安阳县| 上饶县| 重庆市| 甘泉县|