js动态添加style样式

var style = document.createElement("style");

style.type = "text/css";

try{

  style.appendChild(document.createTextNode("body{background-color:red}"));

}catch(ex){

  style.styleSheet.cssText = "body{background-color:red}";//针对IE

}

var head = document.getElementsByTagName("head")[0];

head.appendChild(style);

 

转载于:https://www.cnblogs.com/msg001/p/9280165.html

你可能感兴趣的:(js动态添加style样式)