Home > Article > Web Front-end > Insert styles using javascript_javascript tips
1. Use javascript to insert c9ccee2e6ea535a969eb3f532ad9fe89 style
Sometimes we need to use js to dynamically generate the css code in the style tag on the page. The method is very straightforward, that is, directly create a style element, then set the css code in the style element, and finally insert it into the head element.
But there are some compatibility issues we need to solve. First of all, in browsers that comply with w3c standards, we only need to insert the css code to be inserted into the style element as a text node. In IE, we need to use the styleSheet.cssText of the style element to solve the problem.
It should also be noted that in some versions of IE, the number of style tags on a page is limited. If it is exceeded, an error will be reported. This needs to be considered.
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;}');
Of course, this is just the most basic demonstration method, and it needs to be improved in actual application. For example, insert the css code generated each time into a style element, so that the number of stylesheets will not exceed the limit in IE. Wrong.
Package:
seajs package
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”);
The above is the entire content of this article, I hope it will be helpful to everyone’s study.