Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to generate css Code dynamically by javascript

2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

这篇文章主要讲解了"javascript怎么动态生成css代码",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"javascript怎么动态生成css代码"吧!

javascript 动态生成css代码的两种方法

有时候我们需要利用js来动态生成页面上style标签中的css代码,方法很直接,就是直接创建一个style元素,然后设置style元素里面的css代码,最后把它插入到head元素中。但有些兼容性问题我们需要解决。首先在符合w3c标准的浏览器中我们只需要把要插入的css代码作为一个文本节点插入到style元素中即可,而在IE中则需要利用style元素的styleSheet.cssText来解决。还需要注意的就是在有些版本IE中一个页面上style标签数量是有限制的,如果超过了会报错,需要考虑这点。

方法1:

给标签添加一个id名,在标签中写

var oCss=document.getElementById("css");oCss[xss_clean]+="#box{width:200px;}";

这样就可以加上样式了。

方法2:

有时候我们需要利用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数量超出限制的错误了。

感谢各位的阅读,以上就是"javascript怎么动态生成css代码"的内容了,经过本文的学习后,相信大家对javascript怎么动态生成css代码这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 221

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report