简体   繁体   English

在某些情况下,例如特定于Internet Explorer的CSS或特定于Internet Explorer的JavaScript代码,如何仅将Internet Explorer 10定位?

[英]How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code? 在某些情况下,例如特定于Internet Explorer的CSS或特定于Internet Explorer的JavaScript代码,如何仅将Internet Explorer 10定位?

I tried this, but it doesn't work: 我试过了,但是不起作用:

<!--[if IE 10]>    <html class="no-js ie10" lang="en"> <![endif]-->
<!--[if !IE]><!--> <html lang="en" class="no-js"> <!--<![endif]-->

Internet Explorer 10 ignores the conditional comments and uses the <html lang="en" class="no-js"> instead of <html class="no-js ie10" lang="en"> . Internet Explorer 10忽略条件注释,并使用<html lang="en" class="no-js">而不是<html class="no-js ie10" lang="en">

I wouldn't use JavaScript navigator.userAgent or $.browser (which uses navigator.userAgent ) since it can be spoofed. 我不会使用JavaScript navigator.userAgent$ .browser (使用navigator.userAgent ),因为它可以被欺骗。

To target Internet Explorer 9, 10 and 11 (Note: also the latest Chrome): 要定位Internet Explorer 9、10和11(注意:也是最新的Chrome):

@media screen and (min-width:0\0) { 
    /* Enter CSS here */
}

To target Internet Explorer 10: 要定位Internet Explorer 10:

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    /* IE10+ CSS here */
}

To target Edge Browser: 定位边缘浏览器:

@supports (-ms-accelerator:true) {
  .selector { property:value; } 
}

Sources: 资料来源:

I found a solution on this site where someone had a valuable comment : 我在站点上找到了一个解决方案,有人对此发表了宝贵意见

The solution is: 解决方案是:

if (Function('/*@cc_on return document.documentMode===10@*/')()){
    document.documentElement.className+=' ie10';
}

It

  • doesn't need conditional comments; 不需要条件注释;
  • works even if comment stripping compression/processing; 即使注释条压缩/处理也有效;
  • no ie10 class added in Internet Explorer 11; 在Internet Explorer 11中没有添加ie10类;
  • more likely to work as intended with Internet Explorer 11 running in Internet Explorer 10 compatibility mode; 与以Internet Explorer 10兼容模式运行的Internet Explorer 11更有可能按预期工作;
  • doesn't need standalone script tag (can just be added to other JavaScript code in the head). 不需要独立的脚本标签(可以将其添加到头部的其他JavaScript代码中)。
  • doesn't need jQuery to test 不需要jQuery进行测试

Perhaps you can try some jQuery like this: 也许您可以尝试这样的一些jQuery:

if ($.browser.msie && $.browser.version === 10) {
  $("html").addClass("ie10");
}

To use this method you must include the jQuery Migrate library because this function was removed from the main jQuery library. 要使用此方法,您必须包括jQuery Migrate库,因为此功能已从主jQuery库中删除。

Worked out quite fine for me. 对我来说很好。 But surely no replacement for conditional comments! 但是肯定不能代替条件注释!

Internet Explorer 10 does not attempt to read conditional comments anymore. Internet Explorer 10不再尝试读取条件注释。 This means it will treat conditional comments just like any other browser would: as regular HTML comments, meant to be ignored entirely. 这意味着它将像对待其他浏览器一样对待条件注释:与常规HTML注释一样,它被完全忽略。 Looking at the markup given in the question as an example, all browsers including IE10 will ignore the comment portions, highlighted gray, entirely. 以问题中给出的标记为例,包括IE10在内的所有浏览器都将完全忽略注释部分(突出显示为灰色)。 The HTML5 standard makes no mention of conditional comment syntax, and this is exactly why they have chosen to stop supporting it in IE10. HTML5标准没有提及条件注释语法,这正是他们选择停止在IE10中支持它的原因。

Note, however, that conditional compilation in JScript is still supported, as shown in the comments as well as the more recent answers. 但是请注意,仍然支持JScript中的条件编译 ,如注释和最新答案所示。 It's not going away in the final release either, unlike jQuery.browser . jQuery.browser不同 ,它在最终版本中也不会jQuery.browser And of course, it goes without saying that user-agent sniffing remains as fragile as ever and should never be used under any circumstances. 当然,不用说,用户代理嗅探仍然像以往一样脆弱,在任何情况下都不应使用。

If you really must target IE10, either use conditional compilation which may still see support in the near future, or — if you can help it — use a feature detection library such as Modernizr instead of (or in conjunction with) browser detection. 如果您真的必须以IE10为目标,请使用有条件的编译(可能会在不久的将来获得支持),或者(如果可以帮助您)使用功能检测库(例如Modernizr)来代替(或与浏览器一起检测)。 Unless your use case requires noscript or accommodating IE10 on the server side, user-agent sniffing is going to be more of a headache than a viable option. 除非您的用例需要noscript或在服务器端安装IE10,否则用户代理嗅探将比可行的选择更令人头疼。

Sounds pretty cumbersome, but remember that as a modern browser that's highly conformant to today's Web standards 1 , assuming you've written interoperable code that is highly standards-compliant, you shouldn't have to set aside special code for IE10 unless absolutely necessary, ie it's supposed to resemble other browsers in terms of behavior and rendering. 听起来很麻烦,但请记住,作为一个现代的浏览器这是高度符合的到今天的Web标准1,假设你已经写了互操作的代码是高度符合标准,你不应该为IE10预留特殊的代码,除非绝对必要,也就是说,就行为和渲染而言,它应该类似于其他浏览器。 2 And it sounds far-fetched, given IE's history, but how many times have you expected Firefox or Chrome to behave the same way only to be met with dismay? 2鉴于IE的历史,这听起来有些牵强,但是您期望Firefox或Chrome多少次表现出相同的方式却令人沮丧?

If you do have a legitimate reason to be targeting certain browsers, by all means sniff them out with the other tools given to you. 如果您确实有理由要针对特定​​的浏览器,则一定要使用提供给您的其他工具来将它们嗅出。 I'm just saying that you're going to be much more hard-pressed to find such a reason today than what it used to be, and it's really just not something you can rely on. 我只是说,今天要找到这样的理由比现在要困难得多,而且实际上这不是您可以依靠的。


1 Not only IE10, but IE9, and even IE8 which handles most of the mature CSS2.1 standard far better than Chrome, simply because IE8 was so focused on standards compliance (at which time CSS2.1 was already pretty stable with only minor differences from today's recommendation) while Chrome seems to be little more than a half-polished tech demo of cutting-edge pseudo-standards. 1 不仅IE10,而且IE9甚至是处理大多数成熟CSS2.1标准的IE8都比Chrome更好,这仅仅是因为IE8如此专注于标准合规性(当时CSS2.1已经相当稳定,只有很小的差异)根据今天的建议),而Chrome似乎只是半抛光的尖端伪标准技术演示而已。

2 And I may be biased when I say this, but it sure as hell does. 2 当我这样说时我可能会有偏见,但可以肯定的是。 If your code works in other browsers but not IE, the odds that it's an issue with your own code rather than IE10 are far better compared to, say, 3 years ago, with previous versions of IE. 如果您的代码可以在其他浏览器上运行,但不能在IE上运行,则 3年前的早期版本IE相比, 使用您自己的代码而不是IE10的可能性要大得多。 Again, I may be biased, but let's be honest: aren't you too? 再说一次,我可能有偏见,但说实话: 你不是吗? Just look at your comments. 只要看看您的评论。

A good place to start is the IE Standards Support Documentation . IE标准支持文档是一个不错的起点。

Here is how to target IE10 in JavaScript: 这是在JavaScript中定位IE10的方法:

if ("onpropertychange" in document && !!window.matchMedia) {
...
}

Here is how to target IE10 in CSS: 这是在CSS中定位IE10的方法:

@media all and (-ms-high-contrast: none) {
...
}

In case IE11 needs to be filtered or reset via CSS, see another question: How to write a CSS hack for IE 11? 如果需要通过CSS过滤或重置IE11,请参见另一个问题: 如何为IE 11编写CSS hack?

Both solutions posted here (with slight modifications) work: 此处发布的两种解决方案(稍作修改)都可以工作:

<!--[if !IE]><!--><script>if(/*@cc_on!@*/false){document.documentElement.className='ie10';}</script><!--<![endif]-->

or 要么

<script>if(Function('/*@cc_on return 10===document.documentMode@*/')()){document.documentElement.className='ie10';}</script>

You include either of the above lines inside of head tag of your html page before your css link. 在CSS链接之前,请将以上任一行包含在html页面的head标记内。 And then in css file you specify your styles having "ie10" class as a parent: 然后在css文件中,指定以“ ie10”类作为父类的样式:

.ie10 .myclass1 { }

And voilà! 和瞧! - other browsers stay intact. -其他浏览器保持不变。 And you don't need jQuery. 而且您不需要jQuery。 You can see the example how I implemented it here: http://kardash.net . 您可以在此处查看示例如何实现的示例: http : //kardash.net

I've written a small, vanilla JavaScript plugin called Layout Engine , which allows you to feature detect IE 10 (and every other browser), in a simple way that cannot be faked, unlike user agent sniffing. 我编写了一个名为Layout Engine的小型香草JavaScript插件,该插件可让您以一种无法伪造的简单方式来检测IE 10(以及其他所有浏览器),这与用户代理嗅探不同。

It adds the rendering engine name as a class on the html tag and returns a JavaScript object containing the vendor and version (where appropriate) 它将呈现引擎名称作为类添加到html标记上,并返回包含供应商和版本的JavaScript对象(如果适用)

Check out my blog post: http://mattstow.com/layout-engine.html and get the code on GitHub: https://github.com/stowball/Layout-Engine 查看我的博客文章: http : //mattstow.com/layout-engine.html并在GitHub上获取代码: https : //github.com/stowball/Layout-Engine

I use this script - it's antiquated, but effective in targeting a separate Internet Explorer 10 style sheet or JavaScript file that is included only if the browser is Internet Explorer 10, the same way you would with conditional comments. 我使用此脚本-这是过时的,但是对于定向单独的 Internet Explorer 10样式表或JavaScript文件( 仅当浏览器为Internet Explorer 10 时才包含)是有效的,与使用条件注释的方式相同。 No jQuery or other plugin is required. 不需要jQuery或其他插件。

<script>
    /*@cc_on
      @if (@_jscript_version == 10)
          document.write(' <link type= "text/css" rel="stylesheet" href="your-ie10-styles.css" />');
      @end
    @*/
</script >

You can use PHP to add a stylesheet for IE 10 您可以使用PHP为IE 10添加样式表

Like: 喜欢:

if (stripos($_SERVER['HTTP_USER_AGENT'], 'MSIE 10')) {
    <link rel="stylesheet" type="text/css" href="../ie10.css" />
}

If you must do this, you can check the user agent string in JavaScript: 如果必须执行此操作,则可以在JavaScript中检查用户代理字符串:

var isIE10 = !!navigator.userAgent.match(/MSIE 10/);

As other people have mentioned, I'd always recommend feature detection instead. 正如其他人所提到的,我总是建议使用特征检测。

If you want to target IE 10 with Vanilla JavaScript, you might want to try CSS property detection: 如果要使用Vanilla JavaScript定位IE 10,则可能要尝试CSS属性检测:

if (document.body.style.msTouchAction != undefined) {
  document.body.className = 'ie10';
}

CSS properties CSS属性

Instead of msTouchAction you can also use one of these CSS properties, because they are currently only available in IE 10. But this might change in the future. 除了msTouchAction您还可以使用这些CSS属性之一,因为它们当前仅在IE 10中可用。但是将来可能会改变。

  • msTouchAction msTouchAction
  • msWrapFlow msWrapFlow
  • msWrapMargin msWrapMargin
  • msWrapThrough msWrapThrough
  • msScrollLimit msScrollLimit
  • msScrollLimitXMin msScrollLimitXMin
  • msScrollLimitYMin msScrollLimitYMin
  • msScrollLimitXMax msScrollLimitXMax
  • msScrollLimitYMax msScrollLimitYMax
  • msFlexbox msFlexbox
  • msFlex msFlex
  • msFlexOrder msFlexOrder

Test page 测试页

I've put together a test page with all properties on CodePen. 我将CodePen上所有属性的测试页放在一起。

clipBoardData is a function that is only available in IE, so if you are seeking to target all IE versions you can use clipBoardData是仅在IE中可用的功能,因此,如果要定位所有IE版本,则可以使用

<script type="text/javascript">
if (window.clipboardData)
            alert("You are using IE!");
</script>

CSS for IE10+ and IE9 IE10 +和IE9的CSS

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

@media screen\0 {
    /* IE8,9,10 styles*/
}

You could use feature detection to see if browser is IE10 or greater like so: 您可以使用功能检测来查看浏览器是否为IE10或更高版本,如下所示:

var isIE = false;
if (window.navigator.msPointerEnabled) {
    isIE = true;
}

Only true if > IE9 仅当> IE9时为真

Conditionizr (请参阅文档)会将浏览器CSS类添加到html元素,包括ie10。

With JavaScript: 使用JavaScript:

if (/Trident/g.test(navigator.userAgent)) { // detect trident engine so IE
        document.getElementsByTagName('html')[0].className= 'no-js ie'; }

Work for all IE. 适用于所有IE。

IE08 => 'Trident/4.0'

IE09 => 'Trident/5.0'

IE10 => 'Trident/6.0'

IE11 => 'Trident/7.0'

So change /Trident/g by /Trident/x.0/g where x = 4, 5, 6 or 7 (or maybe 8 for the future). 因此,将/Trident/g更改为/Trident/x.0/g ,其中x = 4, 5, 67 (或者将来可能为8 )。

I just wanted to add my version of IE detection. 我只想添加我的IE检测版本。 It's based on a snippet found at http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/ and exteded to also support ie10 and ie11. 它基于可在http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/找到的摘录,并且还支持ie10和ie11。 It detects IE 5 to 11. 它检测到IE 5到11。

All you need to do is add it somewhere and then you can always check with a simple condition. 您需要做的就是将其添加到某个位置,然后您始终可以通过简单的条件进行检查。 The global var isIE will be undefined if it's not an IE, or otherwise it will be the version number. 如果不是IE,则全局var isIE将是未定义的,否则它将是版本号。 So you can easily add things like if (isIE && isIE < 10) or alike. 因此,您可以轻松添加诸如if (isIE && isIE < 10)之类的内容。

var isIe = (function(){
    if (!(window.ActiveXObject) && "ActiveXObject" in window) { return 11; /* IE11 */ }
    if (Function('/*@cc_on return /^10/.test(@_jscript_version) @*/')()) { return 10; /* IE10  */ }
    var undef,
        v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');
    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
            all[0]
        );
    return v > 4 ? v : undef;
}());

Check out http://suhasrathod.wordpress.com/2013/04/29/ie10-css-hacks/ 查看http://suhasrathod.wordpress.com/2013/04/29/ie10-css-hacks/

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

For me the following code works fine, all conditional comments are working in all IE versions: 对我来说,以下代码可以正常工作,所有条件注释都可以在所有IE版本中使用:

<!--[if lt IE 7 ]> <html class="ie6"> <![endif]-->
<!--[if IE 7 ]>    <html class="ie7"> <![endif]-->
<!--[if IE 8 ]>    <html class="ie8"> <![endif]-->
<!--[if IE 9 ]>    <html class="ie9"> <![endif]-->
<!--[if (gt IE 11)|!(IE)]><!--> <html> <!--<![endif]-->

<script>
    if (document.documentMode===10){
        document.documentElement.className+=' ie10';
    }
    else if (document.documentMode===11){
        document.documentElement.className+=' ie11';
    }
</script>

I'm on windows 8.1, not sure if it's related to ie11 update... 我在Windows 8.1上,不确定是否与ie11更新有关...

Here is how I do custom CSS for Internet Explorer: 这是我为Internet Explorer做自定义CSS的方法:

In my JavaScript file: 在我的JavaScript文件中:

function isIE () {
      var myNav = navigator.userAgent.toLowerCase();
      return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}

jQuery(document).ready(function(){
    if(var_isIE){
            if(var_isIE == 10){
                jQuery("html").addClass("ie10");
            }
            if(var_isIE == 8){
                jQuery("html").addClass("ie8");
                // you can also call here some function to disable things that 
                //are not supported in IE, or override browser default styles.
            }
        }
    });

And then in my CSS file, y define each different style: 然后在我的CSS文件中,定义每个不同的样式:

.ie10 .some-class span{
    .......
}
.ie8 .some-class span{
    .......
}

use babel or typescript for convert this code js 使用babel或打字稿转换此代码js

 const browser = () => { // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3576.0 Safari/537.36" // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.17 Safari/537.36" // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763" // "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0" // "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; rv:11.0) like Gecko" // "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)" // "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)" // "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)" // "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)" const _userAgent = navigator.userAgent; const br = { "Chrome": "Chrome", "Edge": "Edge", "Firefox": "Firefox", ".NET CLR": "Internet Explorer 11", }; const nobr = { "MSIE 10.0": "Internet Explorer 10", "MSIE 9.0": "Internet Explorer 9", "MSIE 8.0": "Internet Explorer 8", "MSIE 7.0": "Internet Explorer 7" }; let thisBrow = "Unknown"; for (const keys in br) { if (br.hasOwnProperty(keys)) { if (_userAgent.includes(keys)) { thisBrow = br[keys]; for (const key in nobr) { if (_userAgent.includes(key)) { thisBrow = nobr[key]; } } } } } return thisBrow; }; 

This answer got me 90% of the way there. 这个答案让我有90%的答案。 I found the rest of my answer on the Microsoft site here . 我在此处Microsoft网站上找到了其余答案。

The code below is what I'm using to target all ie by adding a .ie class to <html> 下面的代码是我用来定位所有目标的代码,即通过向<html>添加.ie类

Use jQuery (which deprecated .browser in favor of user agents in 1.9+, see http://api.jquery.com/jQuery.browser/ ) to add an .ie class: 使用jQuery(在1.9+版本中不推荐使用.browser以便于用户代理,请参见http://api.jquery.com/jQuery.browser/ )来添加.ie类:

// ie identifier
$(document).ready(function () {
  if (navigator.appName == 'Microsoft Internet Explorer') {
    $("html").addClass("ie");
  }
});

If you don't mind targeting of IE10 and above and non IE browsers, you can use this conditional comment: 如果您不介意以IE10及更高版本和非IE浏览器为目标,则可以使用以下条件注释:

<!--[if gt IE 9]><!--> Your code here. <!--<![endif]-->

Derived from http://www.paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither 源自http://www.paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-n

If you really have to, you can make conditional comments work by adding the following line to <head> : 如果确实需要,可以通过将以下行添加到<head>来使条件注释生效:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">

Source 资源

modern solution for css CSS的现代解决方案

html[data-useragent*='MSIE 10.0'] .any {
  your-style: here;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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