Problem description
The following CSS code through JS Dynamic Add, the result will be?
. box { background:red;/* Normal browsers */ *background:blue; /* IE 6 and 7 */ _background:green;/* IE6 */}
Add to the page with the following code
var node = document.createelement (' style '); node.type = ' text/css '; if (node.stylesheet) { //For W3cnode.styleSheet.cssText = style;} else { //For Ienode.appendchild (document.createTextNode (Style));} document.getElementsByTagName (' head ') [0].appendchild (node);
From the code point of view, >=ie8 and modern browser of the. Box color is red , IE7 is blue , IE6 is green , so what is the actual?
IE6:
IE7:
IE8:
Chrome:
What's going on???
As can be seen from the above, only chrome and IE6 are normal, IE7 and IE8 are showing problems.
IE7 's performance for using IE6 hack (_ Hack)
The performance of IE8 is used IE7 hack (* hack)
Workaround
Directly on the code:
var node = document.createelement (' style '); node.type = ' text/css '; document.getelementsbytagname (' head ') [0].appendchild (node); if (node.stylesheet) { //For w3cnode.styleSheet.cssText = style,} else { //for Ienode.appendchild ( document.createTextNode (style));}
In fact, there is no change, that is, moving the appendchild of the code position.
The original CSS style was added to the head, then added to the head, and then updated CSS style.
Refresh IE7 again, 8, now the performance is normal.
Paste the test code:
<! DOCTYPE html>
Reference article: https://www.phpied.com/the-star-hack-in-ie8-and-dynamic-stylesheets/
IE8, 7, 6 when dynamically adding styles, CSS hack bugs