作家
登录

Javascript动态创建 style 节点

作者: 来源:www.28hudong.com 2012-11-19 22:53:22 阅读 我要评论

有很多提供动态创建 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 个字符,长一点的就不行了,经过 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>

  推荐阅读

  CSS:提高网页在浏览器的渲染速度

原文:http://www.zishu.cn/blogview.asp?logID=773 最近很少写CSS了,以后也可能写的会很少了,所以还是想把自已的一些经验能和大家分享一下,希望能给大家一些帮助! 这篇文章主要写的提高网页在客户端浏览器>>>详细阅读


本文标题:Javascript动态创建 style 节点

地址:http://www.17bianji.com/kaifa2/CSS/17335.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)