您好,欢迎访问一九零五行业门户网

使用javascript插入样式_javascript技巧

一、用javascript插入
有时候我们需要利用js来动态生成页面上style标签中的css代码,方法很直接,就是直接创建一个style元素,然后设置style元素里面的css代码,最后把它插入到head元素中。
但有些兼容性问题我们需要解决。首先在符合w3c标准的浏览器中我们只需要把要插入的css代码作为一个文本节点插入到style元素中即可,而在ie中则需要利用style元素的stylesheet.csstext来解决。
还需要注意的就是在有些版本ie中一个页面上style标签数量是有限制的,如果超过了会报错,需要考虑这点。
function addcss(csstext){ var style = document.createelement('style'), //创建一个style元素 head = document.head || document.getelementsbytagname('head')[0]; //获取head元素 style.type = 'text/css'; //这里必须显示设置style元素的type属性为text/css,否则在ie中不起作用 if(style.stylesheet){ //ie var func = function(){ try{ //防止ie中stylesheet数量超过限制而发生错误 style.stylesheet.csstext = csstext; }catch(e){ } } //如果当前stylesheet还不能用,则放到异步中则行 if(style.stylesheet.disabled){ settimeout(func,10); }else{ func(); } }else{ //w3c //w3c浏览器中只要创建文本节点插入到style元素中就行了 var textnode = document.createtextnode(csstext); style.appendchild(textnode); } head.appendchild(style); //把创建的style元素插入到head中 }//使用addcss('#demo{ height: 30px; background:#f00;}');
当然这只是一个最基本的演示方法,实际运用中还需进行完善,比如把每次生成的css代码都插入到一个style元素中,这样在ie中就不会发生stylesheet数量超出限制的错误了。
封装:
复制代码 代码如下:
var importstyle=function importstyle(b){var a=document.createelement(style),c=document;c.getelementsbytagname(head)[0].appendchild(a);if(a.stylesheet){a.stylesheet.csstext=b}else{a.appendchild(c.createtextnode(b))}};
importstyle('h1 { background: red; }');//调用
seajs封装
复制代码 代码如下:
seajs.importstyle=function importstyle(b){var a=document.createelement(style),c=document;c.getelementsbytagname(head)[0].appendchild(a);if(a.stylesheet){a.stylesheet.csstext=b}else{a.appendchild(c.createtextnode(b))}};
二、javascript插入样式
在中使用标签引入一个外部样式文件,这个比较简单,各个主流浏览器也不存在兼容性问题:
function includelinkstyle(url) {var link = document.createelement(“link”);link.rel = “stylesheet”;link.type = “text/css”;link.href = url;document.getelementsbytagname(“head”)[0].appendchild(link);}includelinkstyle(“http://css.xxx.com/home/css/reset.css?v=20101227”);
以上就是本文的全部内容,希望对大家的学习有所帮助。
其它类似信息

推荐信息