Rexdf

The devil is in the Details.

判断IE非IE的几种方法

| Comments

由于浏览器存在各种各样的差异,特别是IE与其他内核浏览器则往往需要特别区分开来对待,但是这种情况直到IE10才缓解,IE10就不支持条件注释了,而对一些CSS3和HTML5新的特性的支持也变得较为友好了。

1.js判断ie非ie的几种方法

以前最短的IE判定借助于IE不支持垂直制表符的特性搞出来的。 var ie = !+"\v1"; 仅仅需要7bytes!参见这篇文章,《32 bytes, ehr … 9, ehr … 7!!! to know if your browser is IE》,讲述外国人是如何把IE的判定从32 bytes一步步缩简成7 bytes!的故事 但这纪录今年1月8日被一个俄国人打破了,现在只要6 bytes!它利用了IE与标准浏览器在处理数组的toString方法的差异做成的。对于标准游览器,如果数组里面最后一个字符为逗号,JS引擎会自动剔除它。详见这里 司徒正美–全世界最短的IE判定 一文,也提到了只有6byte的判断ie与非ie的方法。其 代码如下: [runcode][/runcode] 其实有很多判断的方法,大都是根据浏览器的特性来的。 比如库prototype的方法是:!! (window.attachEvent && navigator.userAgent.indexOf(‘Opera’) === -1) 。就是根据ie支持window.attachEvent添加侦听事件,非ie用window.addEventListener添加侦听事件来判断的。 navigator.userAgent.indexOf(‘Opera’) === -1是因为opara浏览器能伪装成ie.如果!!(window.attachEvent )为真,就是ie;反之,如果!window.addEventListener为真,也可以判断为ie. Ext使用的是!”1”[0],他利用IE无法使用数组下标访问字符串的特性来判断。在ie8下好像有问题。 在!+[1,]还未被发现前,判断ie最短的表达式是 !+”/v1”.它利用的是ie不支持垂直制表符的特性。 以前还有一个常用方法是document.all,由于opera浏览器能伪装成ie。可以这样写:!!(document.all && navigator.userAgent.indexOf(‘Opera’) === -1). 还有很多,先记这几条,便于工作时查阅。

<h4>1.+[1,]</h4>
<h4>2.!+"/v1"</h4>
<h4>3.!!(window.attachEvent &amp;&amp; navigator.userAgent.indexOf('Opera') === -1)</h4>
<h4>4.!!(!window.addEventListener&amp;&amp; navigator.userAgent.indexOf('Opera') === -1)</h4>
<h4>5.!!(document.all &amp;&amp; navigator.userAgent.indexOf('Opera') === -1)</h4>

2.条件注释判断浏览器

除IE外都可识别

项目 范例 说明

! [if !IE] The NOT operator. This is placed immediately in front of the featureoperator, or subexpression to reverse the Boolean meaning of the expression. NOT运算符。这是摆立即在前面的_功能,_操作员,或_子表达式_扭转布尔表达式的意义。

lt [if lt IE 5.5] The less-than operator. Returns true if the first argument is less than the second argument. 小于运算符。如果第一个参数小于第二个参数,则返回true。

lte [if lte IE 6] The less-than or equal operator. Returns true if the first argument is less than or equal to the second argument. 小于或等于运算。如果第一个参数是小于或等于第二个参数,则返回true。

gt [if gt IE 5] The greater-than operator. Returns true if the first argument is greater than the second argument. 大于运算符。如果第一个参数大于第二个参数,则返回true。

gte [if gte IE 7] The greater-than or equal operator. Returns true if the first argument is greater than or equal to the second argument. 大于或等于运算。如果第一个参数是大于或等于第二个参数,则返回true。

( ) [if !(IE 7)] Subexpression operators. Used in conjunction with boolean operators to create more complex expressions. 子表达式运营商。在与布尔运算符用于创建更复杂的表达式。

& [if (gt IE 5)&(lt IE 7)] The AND operator. Returns true if all subexpressions evaluate to true AND运算符。如果所有的子表达式计算结果为true,返回true

| [if (IE 6)|(IE 7)] The OR operator. Returns true if any of the subexpressions evaluates to true. OR运算符。返回true,如果子表达式计算结果为true。 这样有效是有效,但是用HTML VALIDATOR里,报错,因为这个不符合XHTML 1.1的规范, 如果把ELSE语句去掉,则正确. 方法1: 加载CSS2

3.PHP服务端判断

<?php if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE 7.0")){ 
echo '这是IE7';
}else{
echo '不是IE7';
} ?>

Comments