原生js这样写:
var d = document.createElement('style');
d.setAttribute('type', 'text/css');
d.innerHTML = 'p { color: green;}';
document.getElementsByTagName('head')[0].appendChild(d);
如果是动态引入css文件
function addCssByLink(url){如果是jquery
var doc=document;
var link=doc.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", url);
var heads = doc.getElementsByTagName("head");
if(heads.length)
heads[0].appendChild(link);
else
doc.documentElement.appendChild(link);
}
$("head").append("<style>body{color:green;}</style>");动态引入css文件
$("head").append("<link>");
var css = $("head").children(":last");
css.attr({
rel: "stylesheet",
type: "text/css",
href: "/test.css"
});
网友回复