Check if user is using IE

后端 未结 30 1525
心在旅途
心在旅途 2020-11-22 04:34

I am calling a function like the one below by click on divs with a certain class.

Is there a way I can check when starting the function if a user is using Internet

30条回答
  •  北海茫月
    2020-11-22 05:01

    If all you want to know is if the browser is IE or not, you can do this:

    var isIE = false;
    var ua = window.navigator.userAgent;
    var old_ie = ua.indexOf('MSIE ');
    var new_ie = ua.indexOf('Trident/');
    
    if ((old_ie > -1) || (new_ie > -1)) {
        isIE = true;
    }
    
    if ( isIE ) {
        //IE specific code goes here
    }
    

    Update 1: A better method

    I recommend this now. It is still very readable and is far less code :)

    var ua = window.navigator.userAgent;
    var isIE = /MSIE|Trident/.test(ua);
    
    if ( isIE ) {
      //IE specific code goes here
    }
    

    Thanks to JohnnyFun in the comments for the shortened answer :)

    Update 2: Testing for IE in CSS

    Firstly, if you can, you should use @supports statements instead of JS for checking if a browser supports a certain CSS feature.

    .element {
      /* styles for all browsers */
    }
    
    @supports (display: grid) {
      .element {
        /* styles for browsers that support display: grid */
      }
    }
    

    (Note that IE doesn't support @supports at all and will ignore any styles placed inside an @supports statement.)

    If the issue can't be resolved with @supports then you can do this:

    // JS
    
    var ua = window.navigator.userAgent;
    var isIE = /MSIE|Trident/.test(ua);
    
    if ( isIE ) {
      document.documentElement.classList.add('ie')
    }
    
    /* CSS */
    
    .element {
      /* styles that apply everywhere */
    }
    
    .ie .element {
      /* styles that only apply in IE */
    }
    

    (Note: classList is relatively new to JS and I think, out of the IE browsers, it only works in IE11. Possibly also IE10.)

    If you are using SCSS (Sass) in your project, this can be simplified to:

    /* SCSS (Sass) */
    
    .element {
      /* styles that apply everywhere */
    
      .ie & {
        /* styles that only apply in IE */
      }
    }
    

    Update 3: Adding Microsoft Edge (not recommended)

    If you also want to add Microsoft Edge into the list, you can do the following. However I do not recommend it as Edge is a much more competent browser than IE.

    var ua = window.navigator.userAgent;
    var isIE = /MSIE|Trident|Edge\//.test(ua);
    
    if ( isIE ) {
      //IE & Edge specific code goes here
    }
    

提交回复
热议问题