简体   繁体   中英

Show Div Only in Internet Explorer (All Versions)

With Internet Explorer dropping the usage of conditional statements, it makes me puzzled on how one would apply elements or styles separately and only to IE. This no longer works with IE10:

<!--[if IE]>
<![endif]-->

So here is a jsfiddle of a blue and red box: http://jsfiddle.net/74yK9/1/

How would I make the blue box only appear in Internet Explorer (all versions)?

You can do this using jQuery, don't forget to include the jQuery Migrate plugin too:

if ($.browser.msie) {

    // For IE only
    $('#bluebox').show();
} else {

    // all other browsers
    $('#bluebox').hide();
}

Using Javascript, you can use conditional compilation which is only available in IE:

if (Function('/*@cc_on return true@*/')()) {
    // Is IE
}

Modified from here: How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

So the way to use it is something like:

var isIE = false;
if (Function('/*@cc_on return true@*/')()) {
    isIE = true;
    // or
    document.documentElement.className += " isIE";
}

This sets a boolean in Javascript and/or also adds a isIE class to your <html> element...which will be <html class="isIE"> . So that means you can either check the boolean isIE in Javacript, or style things based on the class like:

html.isIE body {
    color: #111;    /* Only applied for IE*/
}

This uses feature detection (kind of) and doesn't use userAgent sniffing. userAgent sniffing is an option, but isn't reliable and is deprecated/removed in modern jQuery.

A little more info on conditional compilation: http://www.javascriptkit.com/javatutors/conditionalcompile.shtml and http://msdn.microsoft.com/en-us/library/ie/121hztk3%28v=vs.94%29.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM