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" οnclick="blue();"/> 
</body>

 

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

转载于:https://www.cnblogs.com/webqiand/p/4325684.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值