针对IE浏览器的不同css [英] Different css for IE browsers

查看:140
本文介绍了针对IE浏览器的不同css的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要为IE运行一些css,而不是其他浏览器。
我使用的是条件注释:

 <! -  [if lt IE 7]>< html class =ie6 ie>百分比抑制率ENDIF]  -  GT!; 
<! - [if IE 7]>< html class =ie7 ie>百分比抑制率ENDIF] - GT!;
<! - [if IE 8]>< html class =ie8 ie>百分比抑制率ENDIF] - GT!;
<! - [if gte IE 9]>< html class =ie>百分比抑制率ENDIF] - GT!;
<! - [!(IE)]><! - >< html class =no-ie> <! - <![ENDIF] - GT;

但是这段代码不适用于IE11并阅读本文 http://reference.sitepoint.com/css/conditionalcomments 我发现之前的版本不再有条件注释。 / p>

然后我尝试用这一行更改第4行

 < ;! -  [if gte IE 9]><! - >< html class =ie> <! - <![ENDIF]  -  GT; 

但是我可以在ie浏览器中看到ie类。



有没有一种巧妙的方法可以区分IE和其他浏览器?

谢谢!

解决方案

回答



您可以使用Javascript来阅读 window.navigator 属性,并从中获取 userAgent 得到的字符串就像这样:

  var agent = window.navigator.userAgent; (agent.indexOf('Trident')> -1)
document.querySelector('body')。classList.add('ie-css');

if

演示这里



如果您需要版本



您可以使用 UA Parser JS 获取包含所有详细信息的好对象。这将是比上面更安全的方法,但您必须包含该库:

  var parser = new UAParser ),
browser = parser.getBrowser();

console.log(browser.name,browser.major); // - > IE 10.0

在这里演示

注意



<您可能会意识到这一点,但使用浏览器嗅探技术是一种古老而糟糕的技术。它会非常快速地导致遗留和不可管理的代码。 尽量避免检测IE版本 使用
功能检测

I need to run some css only for IE and not for other browsers. I was using conditional comments:

<!--[if lt IE 7 ]><html class="ie6 ie"> <![endif]-->
<!--[if IE 7 ]><html class="ie7 ie"> <![endif]-->
<!--[if IE 8 ]><html class="ie8 ie"> <![endif]-->
<!--[if gte IE 9]><html class="ie"> <![endif]-->
<!--[!(IE)]><!--><html class="no-ie"> <!--<![endif]-->

But this code doesn't work for IE11 and reading this article http://reference.sitepoint.com/css/conditionalcomments I discovered that earlier ie versions don't have conditional comments any more.

Then I tried to change the line 4 with this one

<!--[if gte IE 9]><!--><html class="ie"> <!--<![endif]-->

But I can see the ie class also in not ie browsers.

Is there a smart way to distinguish between IE and other browsers?

Thanks!

解决方案

Answer

You can use Javascript to read the window.navigator property and get the userAgent from the resulting string like so:

var agent = window.navigator.userAgent;

if ( agent.indexOf('Trident') > -1 )
  document.querySelector('body').classList.add('ie-css');

Demo Here

If you need versions

You can use UA Parser JS to get a nice object with all the details. This would be a "safer" approach than the above but you must include the library as well:

var parser = new UAParser(),
browser = parser.getBrowser();

console.log( browser.name, browser.major );  // -> "IE 10.0"

Demo Here

Caution

You might be aware of the this but using browser sniffing is an old and bad technique out in the wild. It leads to legacy and unmanageable code very quickly. Try and avoid detecting versions of IE.

Use feature detection instead.

这篇关于针对IE浏览器的不同css的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆