IE8, 7, 6 dynamic Add style, CSS hack bug

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.