【发布时间】:2011-01-30 05:35:13
【问题描述】:
我正在尝试使用这一行来检测浏览器类型:IE 或 Firefox。
alert(isBrowser("Microsoft"));
但我一无所获,甚至没有弹出警报。不知道我做错了什么。
检测浏览器类型的最佳实践方法是什么?
【问题讨论】:
标签: javascript internet-explorer firefox
我正在尝试使用这一行来检测浏览器类型:IE 或 Firefox。
alert(isBrowser("Microsoft"));
但我一无所获,甚至没有弹出警报。不知道我做错了什么。
检测浏览器类型的最佳实践方法是什么?
【问题讨论】:
标签: javascript internet-explorer firefox
【讨论】:
试试这个:
alert(navigator.appName);
【讨论】:
我认为当 jQuery 支持 testing for features 而不仅仅是浏览器时,它是正确的。
【讨论】:
对于 MSIE 检测,您可以使用 JavaScript:
// This function returns Internet Explorer's major version number,
// or 0 for others. It works by finding the "MSIE " string and
// extracting the version number following the space, up to the decimal
// point, ignoring the minor version number
<SCRIPT LANGUAGE="JavaSCRIPT">
function msieversion()
{
var ua = window.navigator.userAgent
var msie = ua.indexOf ( "MSIE " )
if ( msie > 0 ) // If Internet Explorer, return version number
return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )))
else // If another browser, return 0
return 0
}
</SCRIPT>
以下是如何在 html 中的任何位置调用它的示例:
<SCRIPT LANGUAGE="javascript">
if ( msieversion() >= 0 )
document.write ( "This is Internet Explorer" );
else
document.write ( "This is another browser" );
</SCRIPT>
http://support.microsoft.com/kb/167820 http://support.microsoft.com/kb/167820
【讨论】:
Quirksmode 的一篇非常好的文章来自于:http://www.quirksmode.org/js/support.html
'lajuette' 提供的脚本很好,但不会让你变得更聪明。同一作者在上面的链接中解释了他对脚本背后的想法,基本上他说的是:
【讨论】:
This is basic for browser type detection 但是从这个小代码中很难理解出了什么问题......你可以添加 isBrowser() 的正文来帮助吗?
【讨论】:
function whereUWantToDetectBrowser(){
if (navigator.appName == "Microsoft Internet Explorer")
intExp();
else
other();
}
function intExp(){
//do what you want to do for specifically Internet Explorer
}
function other(){
//do what you want to do for other browsers
}
这段代码解决了这个问题。如果您在此处编写特定代码,而不是从whereUWantToDetectBrowser() 调用函数,这将导致错误。并且代码不会运行。因为浏览器检测到它必须运行的代码(特定于每个浏览器)。如果您要区分代码,则意味着该代码在某些浏览器中不起作用,因此您想专门为这些浏览器编写它。
所以other()在IE下是无效的,因为intExp()在其他浏览器下是无效的。
【讨论】:
查找 IE 浏览器类型的最佳和最短的方法是.. 其他浏览器类型也可以这样做
if (navigator.appName == "Microsoft Internet Explorer"){
// Ur piece of validation
}
【讨论】: