Adding a style tag to a page
I'm trying to add some styles into a page using javascript
var style = document.createElement("style"),
style.innerHTML = ".firstChildTest div:first-child {width: 2px;}";
But ie6-8 are throwing an error when trying开发者_开发问答 to use innerHTML on a style element. I also get the same error using
style.append(document.createTextNode(".firstChildTest div:first-child {width: 2px;}"));
How do I inject styles into a style element in ie?
See the answer here: How do you copy an inline style element in IE?
function copy_style(style_text) {
var tmp_div = document.createElement('div');
tmp_div.innerHTML = '<p>x</p><style type="text/css">' + style_text + '</style>';
return tmp_div.getElementsByTagName('style')[0];
}
Note that you need the <p>
tag in the innerHTML of the tmp_div. Without it, IE does not accept the style element.
IE before #9 cannot use childNodes to add text to a style (or script or option) element, And styles are supposed to be in the head of an html document.
function addStyle(str){
var el= document.createElement('style');
if(el.styleSheet) el.styleSheet.cssText= str;
else{
el.appendChild(document.createTextNode(str));
}
return document.getElementsByTagName('head')[0].appendChild(el);
}
精彩评论