Writing Conditional Code for Internet Explorer WIT

2019-05-11 07:12发布

I'd like to know if it's possible to write conditional javascript within a javascript file for Internet Explorer.

i.e. something like this...

if (is IE7) {
    do this } else {
    do this instead
});

I know I can load a completely different script for IE using conditional comments in the head, but I only want to change a small piece of code and so loading a completely different sheet would be an 'expensive' way to do that.

7条回答
何必那么认真
2楼-- · 2019-05-11 07:25

Despite the fact that this is an answer to the original question, this is NOT what you should do. So don't do it!

Why not work out which browser you are using and store that in a variable in javascript. Then you can have if statemenets and the like in your javascript. e.g. If I am IE then do this, otherwise do that. You get the idea!

Have you seen this? Browser sniffing

The salient bit:

var is = {
  ff: window.globalStorage,
  ie: document.all && !window.opera,
  ie6: !window.XMLHttpRequest,
  ie7: document.all && window.XMLHttpRequest && !XDomainRequest && !window.opera,
  ie8: document.documentMode==8,
  opera: Boolean(window.opera),
  chrome: Boolean(window.chrome),
  safari: window.getComputedStyle && !window.globalStorage && !window.opera
}
查看更多
够拽才男人
3楼-- · 2019-05-11 07:27

My go-to script for this is PPK's BrowserDetect script. It's lightweight, easily understandable, and doesn't require you to use a library. When it's loaded, you can write code like:

if (BrowserDetect.browser == "Explorer" && BrowserDetect.version >= 6 && BrowserDetect.version <= 8) {
    // IE6-8 code
{

Of course, you should avoid using this at all (reasonable) costs, but there's times where it's cleaner to quarantine IE-specific code away rather than try to hack around IE-specific functions and bugs.

查看更多
4楼-- · 2019-05-11 07:33

If you are using jquery you code do this

if ($.browser.msie && $.browser.version == '6.0') {
     //do IE specific code
}
查看更多
姐就是有狂的资本
5楼-- · 2019-05-11 07:38

If you want to use jquery, it has a built in browser detect.

http://api.jquery.com/jQuery.browser/

查看更多
成全新的幸福
6楼-- · 2019-05-11 07:43

Conditional compilation is exactly what you are looking for.

<script>
/*@cc_on

  @if (@_jscript_version == 5.7 && window.XMLHttpRequest)
    document.write("You are using IE7");

  @end

@*/
</script>
查看更多
地球回转人心会变
7楼-- · 2019-05-11 07:44

Not within the JavaScript file directly.

A few alternatives would be:

Using a global variable before the script is loaded to check in your JavaScript file. This is a bit of a hybrid approach and could get messy, but it's guaranteed IE detection.

<!--[if IE]>
<script type="text/javascript">
  var is_ie = true;
</script>
<![endif]-->
<script type="text/javascript" src="somefile.js"></script>

Or, a more traditional approach using browser or object detection within the JavaScript file.

查看更多
登录 后发表回答