javascript 检测浏览器是否为 IE 7 或更低版本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6104109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect whether browser is IE 7 or lower?
提问by ellisgeek
So i am going to add a redirect to my site to toss every one that is using ie 7 or lower off to a different page and came up with this JavaScript, but it seems to have stopped working.
因此,我将添加一个重定向到我的站点,以将所有使用 ie 7 或更低版本的站点都扔到不同的页面并使用此 JavaScript,但它似乎已停止工作。
<script type="text/javascript">
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
var ieversion=new Number(RegExp.) // capture x.x portion and store as a number
if (ieversion<=8)
window.location = "ie.html"
}
window.location = "main.html"
</script>
采纳答案by p.campbell
Your code is always resulting to having gone to main.html
. Even when the code falls into <8
, you'll fall out of the if
into setting to main
.
您的代码总是导致转到main.html
. 即使代码落入<8
,您也会脱离if
进入设置为main
。
Consider refactoring by either:
考虑通过以下任一方式进行重构:
- setting a
return
after setting toie
.
- 设置
return
后设置为ie
。
or
或者
var redir="main.html";
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
{
var ieversion=new Number(RegExp.);
if (ieversion<=8)
{
redir = "ie.html";
}
}
window.location = redir;
回答by Kon
Check out conditional comments.
查看条件注释。
So you can do something like:
因此,您可以执行以下操作:
<script type="text/javascript">
<!--[if (!IE)|(gt IE 7)]>
window.location = "ie.html"
<![endif]-->
<!--[if lt IE 8]>
window.location = "main.html"
<![endif]-->
</script>
回答by Tim Down
Conditional comments (as suggested by @Kon) are the way to go. Here's a working implementation:
有条件的评论(如@Kon 所建议的)是要走的路。这是一个有效的实现:
<script type="text/javascript">
var ie7OrLower = false;
</script>
<!--[if lte IE 7]><script type="text/javascript">
ie7OrLower = true;
</script><![endif]-->
<script type="text/javascript">
window.location = ie7OrLower ? "ie.html" : "main.html";
</script>
回答by Technotronic
You can test it with this regular expression: (MSIE\ [0-7]\.\d+)
你可以用这个正则表达式测试它: (MSIE\ [0-7]\.\d+)
Here is a JavaScript example on how to use it:
这是一个关于如何使用它的 JavaScript 示例:
if (/(MSIE\ [0-7]\.\d+)/.test(navigator.userAgent)) {
// do something
}
回答by James Hill
I've always used Quirks Mode's BrowserDetect.js for my browser detection needs. Check it out - http://www.quirksmode.org/js/detect.html
我一直使用 Quirks Mode 的 BrowserDetect.js 来满足我的浏览器检测需求。检查一下 - http://www.quirksmode.org/js/detect.html
Once you've referenced the .js file, you can access lots of information:
引用 .js 文件后,您可以访问大量信息:
//Browser Name
BrowserDetect.browser
//Browser Version
BrowserDetect.version
//Operating system
BrowserDetect.OS
回答by DGM
I'd just use the examples at http://www.ie6nomore.com/
我只是使用http://www.ie6nomore.com/ 上的示例