Detección de IE11 utilizando la Capacidad de CSS / Detección de Características


IE10+ ya no admite etiquetas de detección de navegador para identificar un navegador.

Para detectar IE10 estoy usando JavaScript y una técnica de prueba de capacidad para detectar ciertos estilos prefijados ms se definen como msTouchAction y msWrapFlow.

Quiero hacer lo mismo para IE11, pero estoy asumiendo que todos los estilos IE10 serán soportados en IE11 también. ¿Puede alguien ayudarme a identificar solo los estilos o capacidades de IE11 que podría usar para distinguir los dos?

Extra Info

  • No quiero usar la detección de tipo de Agente de usuario porque es tan irregular, y se puede cambiar, así como creo que he leído que IE11 está tratando intencionalmente de ocultar el hecho de que es Internet Explorer.
  • Para un ejemplo de cómo funciona la prueba de capacidad de IE10, utilicé este JsFiddle (no mío) como base para mi prueba.
  • También estoy esperando muchas respuestas de "Esto es una mala idea...". Una de mis necesidades para esto es que IE10 afirma que es compatible algo, pero está muy mal implementado, y quiero poder diferenciar entre IE10 e IE11+ para poder seguir adelante con un método de detección basado en capacidades en el futuro.
  • Esta prueba se combina con una prueba de Modernizr que simplemente hará que alguna funcionalidad "fallback" a un comportamiento menos glamuroso. No estamos hablando de funcionalidad crítica.

También ya estoy usando Modernizr, pero no ayuda aquí. Necesito ayuda para una solución a mi claramente pedido pregunta por favor.

Author: piperchester, 2013-09-20

17 answers

A la luz del hilo evolutivo, he actualizado lo siguiente:

IE 6

* html .ie6 {property:value;}

O

.ie6 { _property:value;}

IE 7

*+html .ie7 {property:value;}

O

*:first-child+html .ie7 {property:value;}

ES decir, 6 y 7

@media screen\9 {
    .ie67 {property:value;}
}

O

.ie67 { *property:value;}

O

.ie67 { #property:value;}

ES decir, 6, 7 y 8

@media \0screen\,screen\9 {
    .ie678 {property:value;}
}

IE 8

html>/**/body .ie8 {property:value;}

O

@media \0screen {
    .ie8 {property:value;}
}

ES decir, Solo Modo Estándar de 8

.ie8 { property /*\**/: value\9 }

ES decir, 8,9 y 10

@media screen\0 {
    .ie8910 {property:value;}
}

IE 9 solamente

@media screen and (min-width:0\0) and (min-resolution: .001dpcm) { 
 // IE9 CSS
 .ie9{property:value;}
}

IE 9 y superior

@media screen and (min-width:0\0) and (min-resolution: +72dpi) {
  // IE9+ CSS
  .ie9up{property:value;}
}

IE 9 y 10

@media screen and (min-width:0) {
    .ie910{property:value;}
}

ES decir, solo 10

_:-ms-lang(x), .ie10 { property:value\9; }

IE 10 y superior

_:-ms-lang(x), .ie10up { property:value; }

O

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
   .ie10up{property:value;}
}

El uso de -ms-high-contrast significa que MS Edge no será el objetivo, ya que Edge no admite -ms-high-contrast.

IE 11

_:-ms-fullscreen, :root .ie11up { property:value; }

Alternativas de Javascript

Modernizr

Modernizr se ejecuta rápidamente en la carga de la página para detectar características; entonces crea un objeto JavaScript con los resultados, y añade clases a la HTML elemento

Selección del agente de usuario

Javascript:

var b = document.documentElement;
        b.setAttribute('data-useragent',  navigator.userAgent);
        b.setAttribute('data-platform', navigator.platform );
        b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

Añade (por ejemplo) lo siguiente al elemento html:

data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'

Permite selectores CSS muy dirigidos, por ejemplo:

html[data-useragent*='Chrome/13.0'] .nav{
    background:url(img/radial_grad.png) center bottom no-repeat;
}

Nota de pie de página

Si es posible, identifique y corrija cualquier problema sin hacks. Apoyo mejora progresiva y la degradación de la. Sin embargo, este es un escenario de 'mundo ideal' no siempre obtenible, ya que tal-lo anterior debe ayudar a proporcionar algunas buenas opciones.


Atribución / Lectura esencial

 118
Author: SW4,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-06 03:10:30

Así que al final encontré mi propia solución a este problema.

Después de buscar a través de documentación de Microsoft Me las arreglé para encontrar un nuevo IE11 solo estilo msTextCombineHorizontal

En mi prueba, compruebo los estilos IE10 y si son una coincidencia positiva, entonces compruebo el estilo solo IE11. Si lo encuentro, entonces es IE11+, si no, entonces es IE10.

Ejemplo de Código: Detectar IE10 e IE11 mediante Pruebas de capacidad CSS (JSFiddle)

 /**
  Target IE 10 with JavaScript and CSS property detection.
  
  # 2013 by Tim Pietrusky
  # timpietrusky.com
 **/

 // IE 10 only CSS properties
 var ie10Styles = [
     'msTouchAction',
     'msWrapFlow',
     'msWrapMargin',
     'msWrapThrough',
     'msOverflowStyle',
     'msScrollChaining',
     'msScrollLimit',
     'msScrollLimitXMin',
     'msScrollLimitYMin',
     'msScrollLimitXMax',
     'msScrollLimitYMax',
     'msScrollRails',
     'msScrollSnapPointsX',
     'msScrollSnapPointsY',
     'msScrollSnapType',
     'msScrollSnapX',
     'msScrollSnapY',
     'msScrollTranslation',
     'msFlexbox',
     'msFlex',
     'msFlexOrder'];

 var ie11Styles = [
     'msTextCombineHorizontal'];

 /*
  * Test all IE only CSS properties
  */
 var d = document;
 var b = d.body;
 var s = b.style;
 var ieVersion = null;
 var property;

 // Test IE10 properties
 for (var i = 0; i < ie10Styles.length; i++) {
     property = ie10Styles[i];

     if (s[property] != undefined) {
         ieVersion = "ie10";
         createEl("IE10 style found: " + property);
     }
 }

 // Test IE11 properties
 for (var i = 0; i < ie11Styles.length; i++) {
     property = ie11Styles[i];

     if (s[property] != undefined) {
         ieVersion = "ie11";
         createEl("IE11 style found: " + property);
     }
 }

 if (ieVersion) {
     b.className = ieVersion;
     $('#versionId').html('Version: ' + ieVersion);
 } else {
     createEl('Not IE10 or 11.');
 }

 /*
  * Just a little helper to create a DOM element
  */
 function createEl(content) {
     el = d.createElement('div');
     el.innerHTML = content;
     b.appendChild(el);
 }

 /*
  * List of IE CSS stuff:
  * http://msdn.microsoft.com/en-us/library/ie/hh869403(v=vs.85).aspx
  */
body {
    font: 1.25em sans-serif;
}
div {
    background: red;
    color:#fff;
    padding: 1em;
}
.ie10 div {
    background: green;
    margin-bottom:.5em;
}
.ie11 div {
    background: purple;
    margin-bottom:.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h1>Detect IE10 and IE11 by CSS Capability Testing</h1>


<h2 id="versionId"></h2>

Actualizaré el ejemplo de código con más estilos cuando los descubra.

NOTA: Esto casi seguramente identificará IE12 e IE13 como "IE11", ya que esos estilos probablemente seguirán adelante. Agregaré más pruebas a medida que se implementen nuevas versiones, y espero poder confiar nuevamente en Modernizr.

Estoy usando esta prueba para el comportamiento alternativo. El comportamiento alternativo es solo un estilo menos glamuroso, no tienen funcionalidad reducida.

 23
Author: Evildonald,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-04 13:38:28
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  

}

Agregue todas sus clases o propiedades CSS.

 15
Author: Apps Tawale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-30 01:37:51

Esto parece funcionar:

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
}

Https://www.limecanvas.com/css-hacks-for-targeting-ie-10-and-above /

 10
Author: geoff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-15 04:16:26

Puede escribir su código IE11 como normal y luego usar @supports y comprobar si hay una propiedad que no esté soportada en IE11, por ejemplo grid-area: auto.

Luego puede escribir sus estilos de navegador modernos dentro de esto. IE ignorará la regla @supports y utilizará los estilos originales, mientras que estos se anularán en los navegadores modernos.

.my-class {
// IE the background will be red
background: red;

   // Modern browsers the background will be blue
    @supports (grid-area: auto) {
      background: blue;
    }
}
 4
Author: Antfish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-18 14:15:35

Esto funcionó para mí

if(navigator.userAgent.match(/Trident.*rv:11\./)) {
    $('body').addClass('ie11');
}

Y luego en el archivo css cosas con el prefijo

body.ie11 #some-other-div

¿Cuándo está listo este navegador para morir?

 3
Author: Bert Oost,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-25 07:52:33

Echa un vistazo a este artículo: CSS: User Agent Selectors

Básicamente, cuando se utiliza este script:

var b = document.documentElement;
b.setAttribute('data-useragent',  navigator.userAgent);
b.setAttribute('data-platform', navigator.platform );
b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

Ahora puede usar CSS para dirigirse a cualquier navegador / versión.

Así que para IE11 podríamos hacer esto:

FIDDLE

html[data-useragent*='rv:11.0']
{
    color: green;
}
 3
Author: Danield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-16 11:21:09

Prueba esto:

/*------Specific style for IE11---------*/
 _:-ms-fullscreen, :root 
 .legend 
{ 
  line-height: 1.5em;
  position: relative;
  top: -1.1em;   
}
 3
Author: Mahyar Farshi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-09 18:41:45

Aquí hay una respuesta para 2017, donde probablemente solo te importe distinguir IE11 ("Edge"):

@supports not (old: ie) { /* code for not old IE here */ }

Ejemplo más demostrativo:

body:before { content: 'old ie'; }
/**/@supports not (old: ie) {
body:before { content: 'not old ie'; }
/**/}

Esto funciona porque IE11 en realidad ni siquiera soporta @supports, y todas las otras combinaciones relevantes de navegador/versión lo hacen.

También es probable que exista alguna propiedad propietaria -ms-foo que admite IE11 pero >IE11 no admite, en cuyo caso podría usar @supports (--what: evr) { } para dirigirse directamente a IE11 solo en su lugar sobre el uso de la anulación antes mencionada.

 3
Author: Jan Kyu Peblik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-03 20:36:12

Debe usar Modernizr, agregará una clase a la etiqueta body.

También:

function getIeVersion()
{
  var rv = -1;
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  else if (navigator.appName == 'Netscape')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

Tenga en cuenta que IE11 todavía está en vista previa, y el agente de usuario puede cambiar antes del lanzamiento.

La cadena de agente de usuario para IE 11 es actualmente esta:

Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko

Lo que significa que puede simplemente probar, para las versiones 11.xx,

var isIE11 = !!navigator.userAgent.match(/Trident.*rv 11\./)
 2
Author: Neo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-20 00:52:49

Quizás Layout Engine v0.7.0 sea una buena solución para su situación. Utiliza la detección de funciones del navegador y puede detectar no solo IE11 e IE10, sino también IE9, IE8 e IE7. También detecta otros navegadores populares, incluidos algunos navegadores móviles. Agrega una clase a la etiqueta html, es fácil de usar y se realiza bien bajo algunas pruebas bastante profundas.

Http://mattstow.com/layout-engine.html

 2
Author: Talkingrock,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-20 02:23:40

Si está utilizando Modernizr, entonces puede diferenciar fácilmente entre IE10 e IE11.

IE10 no soporta la propiedad pointer-events. IE11 lo hace. (caniuse )

Ahora, basado en la clase que inserta Modernizr, podría tener el siguiente CSS:

.class
{ 
   /* for IE11 */
}

.no-pointerevents .class
{ 
   /* for IE10 */
}
 2
Author: Danield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-30 14:57:26

Puede usar js y agregar una clase en html para mantener el estándar de comentarios condicionales :

  var ua = navigator.userAgent,
      doc = document.documentElement;

  if ((ua.match(/MSIE 10.0/i))) {
    doc.className = doc.className + " ie10";

  } else if((ua.match(/rv:11.0/i))){
    doc.className = doc.className + " ie11";
  }

O usa una lib como bowser:

Https://github.com/ded/bowser

O modernizr para la detección de características:

Http://modernizr.com/

 2
Author: Liko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:30

Utilice las siguientes propiedades:

  • !!ventana.MSInputMethodContext
  • !!documento.msFullscreenEnabled
 2
Author: Paul Sweatte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-28 02:29:11

Detectar IE y sus versiones en realidad es extremadamente fácil, al menos extremadamente intuitivo:

var uA = navigator.userAgent;
var browser = null;
var ieVersion = null;

if (uA.indexOf('MSIE 6') >= 0) {
    browser = 'IE';
    ieVersion = 6;
}
if (uA.indexOf('MSIE 7') >= 0) {
    browser = 'IE';
    ieVersion = 7;
}
if (document.documentMode) { // as of IE8
    browser = 'IE';
    ieVersion = document.documentMode;
}

.

De esta manera, también estamos capturando versiones IE altas en Modo/Vista de compatibilidad. A continuación, se trata de asignar clases condicionales:

var htmlTag = document.documentElement;
if (browser == 'IE' && ieVersion <= 11)
    htmlTag.className += ' ie11-';
 2
Author: Frank Conijn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-14 02:00:55

Puedes probar esto:

if(document.documentMode) {
  document.documentElement.className+=' ie'+document.documentMode;
}
 2
Author: Adrian Miranda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-13 18:48:18

Paso atrás: ¿por qué está tratando de detectar "Internet explorer" en lugar de "mi sitio web necesita hacer X, este navegador admite esa función? Si es así, buen navegador. Si no, entonces debo advertir al usuario".

Usted debe golpear para arriba http://modernizr.com / en lugar de continuar con lo que estás haciendo.

 1
Author: Mike 'Pomax' Kamermans,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-17 07:33:27