javascript动态创建并执行css代码实例
分类:实例代码
在实际应用中,可能需要动态的创建相关的css并执行。
下面分享两段能够实现此功能的代码,需要的朋友可以做一下参考。
代码实例一:
var flag = true; if(flag){ var style = docuemnt.createElement('style'); style.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(style); insertRule(document.styleSheets[0],'#box','background:red',0); } function insertRule(sheet,selectorText,cssText,position){ // 如果是非IE; if(sheet.insertRule){ sheet.insertRule(selectorText+"{"+cssText+"}",position); // 如果是IE; }else if(sheet.addRule){ sheet.addRule(selectorText,cssText,position); } }
代码实例二:
function loadStyleString(css){ var style = document.createElement("style"); style.type = "text/css"; try{ // IE会报错;不允许向<style>元素添加子节点; style.appendChild(document.createTextNode(css)); }catch(ex){ // 此时,访问元素的StyleSheet属性,该属性有有一个cssText属性,可以接受CSS代码; style.styleSheet.cssText = css; } var head = document.getElementsByTagName("head")[0]; head.appendChild(style); } // 调用; loadStyleString("body {background-color:red}");