javascript在页面head内动态插入style
纯js实现:
var css = 'h1 { background: red; }', head = document.getElementsByTagName('head')[0], style = document.createElement('style'); style.type = 'text/css'; if(style.styleSheet){ style.styleSheet.cssText = css; }else{ style.appendChild(document.createTextNode(css)); } head.appendChild(style);
jquery实现:
var $style = $('<style type="text/css"></style>'); $($('head')[0]).append($style); $style.append('.test{background: red;}');