您的位置:首页 > Web前端 > JavaScript

用javascript插入样式

2017-05-16 17:56 134 查看

一、用javascript插入<style>样式

有时候我们需要利用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插入<link>样式

在<head>中使用<link>标签引入一个外部样式文件,这个比较简单,各个主流浏览器也不存在兼容性问题:

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”);


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: