开发者

ie conditional comments need explanation

The following code is for reliable cross-browser IE version detection

<!--[if lt IE 7 ]><body class="ie_6"><![endif]-->
<!--[if IE 7 ]><body class="ie_7"><![endif]-->
<!--[if IE 8 ]><body class="ie_8"><![endif]-->
<!--[if IE 9 ]><body class="ie_9"><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!-->
<body>
<!--<![endif]-->

What I don't understand is, why it's working.Why the normal 开发者_如何学Python<body> didn't overwrite the <body class="ie_9"> since it is just a normal tag, should be recognized by all the browsers.

What's the magic about

    <!-->
    <body>
    <!--


You probably want to change !(IE) to (!IE)

Also, the "normal" <body> tag you're talking about is in a conditional comment. The fact that it's on a different line doesn't matter, it's still inside the conditional comment tag, so is affected as such.

Conditional comments for IE work by using normal HTML comments <!-- --> so any code inside a "false" conditional is just commented out; <!-- <body class="ie6"> --> IE then has its own syntax inside of that. As such, non-IE browsers just see a commented string, and IE treats it as a statement to execute.

Because of this, only one body tag shows, and only that one gets used.


More explanation of

<!--[if (gt IE 9)|!(IE)]><!-->
<body>
<!--<![endif]-->

To IE, this says:

<if greater than ie9, or not ie> (ie conditional comment)
<!--> (empty comment) (--> putting this here to stop SO ruining syntax highlighting :D)
<body>
<end if> (ie conditional comment)

If you don't understand why, read the paragraph starting "Conditional comments for IE work...".

This same block, to any other browser looks like this:

<!--[if (gt IE 9)|!(IE)]><!--> (this is just one comment, containing the text "[if (gt IE 9)|!(IE)]><!")
<body>
<!--<![endif]--> (again, just one comment, containing "<![endif]")


<!--[if (gt IE 9)|!(IE)]><!-->
<body>
<!--<![endif]-->

means: Ouput the <body> there if the browser version is greater than (gt) IE9 (so, e.g. IE10) or if it is not IE.

Since IE9 is currently the latest version, this condition is not fulfilled by any IE.

The trick is that --> in the first line will close the comment in other browsers, so for them, <!--[if (gt IE 9)|!(IE)]><!--> is just a normal comment (same for <!-- at the last line).

But IE will parse <!--[if (gt IE 9)|!(IE)]> and <![endif]-->, and treat <!--><body><!-- as the content of the conditional comment. Which means, that if the condition is fulfilled, it outputs an empty comment, the <body> tag, and beginning of a comment.

MSDN has a comprehensive description about conditional comments. It seems you could achieve the same by using Downlevel-revealed Conditional Comments:

<![if (gt IE 9)|!(IE)]>
<p>Please upgrade to Internet Explorer version 8.</p>
<![endif]>

(though it is not valid HTML).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜