Conditional Comments in Internet Explorer

犀牛书

Conditional Comments in Internet Explorer
In practice, you'll find that many of the incompatibilities in client-side JavaScript programming turn out to be IE-specific. That is, you must write code in one way for IE and in another way for all other browsers. Although you should normally avoid browser-specific extensions that are not likely to be standardized, IE supports conditional comments in both HTML and JavaScript code that can be useful.

Here is what conditional comments in HTML look like. Notice the tricks played with the closing delimiter of HTML comments:

<!--[if IE]>
This content is actually inside an HTML comment.
It will only be displayed in IE.
<![endif]-->

<!--[if gte IE 6]>
This content will only be displayed by IE 6 and later.
<![endif]-->

<!--[if !IE]> <-->
This is normal HTML content, but IE will not display it
because of the comment above and the comment below.
<!--> <![endif]-->

This is normal content, displayed by all browsers.


Conditional comments are also supported by IE's JavaScript interpreter, and C and C++ programmers may find them similar to the #ifdef/#endif functionality of the C preprocessor. A JavaScript conditional comment in IE begins with the text /*@cc_on and ends with the text @*/. (The cc in cc_on stands for conditional compilation.) The following conditional comment includes code that is executed only in IE:

/*@cc_on
@if (@_jscript)

// This code is inside a JS comment but is executed in IE.
alert("In IE");

@end
@*/


Inside a conditional comment, the keywords @if, @else, and @end delimit the code that is to be conditionally executed by IE's JavaScript interpreter. Most of the time, you need only the simple conditional shown above: @if (@_jscript). JScript is Microsoft's name for its JavaScript interpreter, and the @_jscript variable is always true in IE.

With clever interleaving of conditional comments and regular JavaScript comments, you can set up one block of code to run in IE and a different block to run in all other browsers:

/*@cc_on
@if (@_jscript)
// This code is inside a conditional comment, which is also a
// regular JavaScript comment. IE runs it but other browsers ignore it.
alert('You are using Internet Explorer);
@else*/
// This code is no longer inside a JavaScript comment, but is still
// inside the IE conditional comment. This means that all browsers
// except IE will run this code.
alert('You are not using Internet Explorer');
/*@end
@*/


Conditional comments, in both their HTML and JavaScript forms, are completely nonstandard. They are sometimes a useful way to achieve compatibility with IE, however.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值