本文介绍两种使用原生JavaScript检测IE8及以下浏览器版本的方法。第一种通过解析userAgent字符串中的MSIE标识获取版本号;第二种利用IE特有的documentMode属性判断文档渲染模式。文章提供了相应的代码示例,用于在检测到低版本IE时进行特殊处理或提示用户。
使用原生JavaScript检测当前IE浏览器版本是否为IE8及更低版本,并在满足条件时给出相应提示,具体实现代码如下:
方法一:通过userAgent判断
首先获取浏览器的userAgent字符串,随后利用正则表达式匹配其中的版本信息。
var DEFAULT_VERSION = 8.0;
var ua = navigator.userAgent.toLowerCase();
var isIE = ua.indexOf("msie")>-1;
var safariVersion;
if(isIE){
safariVersion = ua.match(/msie ([\d.]+)/)[1];
}
if(safariVersion <= DEFAULT_VERSION ){
// 进行你所要的操作
$(".wrap").before('<div class="low_version">系统检测到您正在使用ie8以下内核的浏览器,不能实现完美体验,请及时更新浏览器版本!</div>');
};方法二:通过documentMode判断
尽管IE浏览器逐渐退出历史舞台,但在某些项目中仍需保持对其的支持。因此,必须准确判断当前是否为IE浏览器,若是,则需执行特定的兼容处理逻辑。
document.documentMode是IE浏览器特有的属性,可以通过检查该属性是否存在来判断是否为IE浏览器。例如:
var isIE = document.documentMode !== undefined;
这种方法确实简单且实用。
通常情况下,document.documentMode的值直接对应IE的版本号,具体对应关系如下:
7 - The page is displayed in IE7 mode 8 - The page is displayed in IE8 mode 9 - The page is displayed in IE9 mode 10 - The page is displayed in IE10 mode 11 - The page is displayed in IE11 mode
function IEVersion () {
if (document.documentMode) return document.documentMode;
}
if (IEVersion()<=8) {
alert("低于ie8");
}关于documentMode属性
1、定义和用法:
The documentMode property returns the mode used by the browsers to render the current document.
documentMode属性用于返回浏览器渲染当前文档所采用的模式。
IE8 can render a page in different modes,depending on the !DOCTYPE or the presence of certain HTML elements.
IE8可以根据!DOCTYPE声明或特定HTML元素的存在与否,以不同的模式来渲染页面。
该属性返回以下对应的值:
5 ----- in IE5 mode 7 ----- in IE7 mode 8 ----- in IE8 mode 9 ----- in IE9 mode 注释: 如果没有定义!DOCTYPE,IE8以IE5的模式来渲染页面
2、语法:
document.documentMode
3、浏览器支持:
documentMode是一个IE私有属性,仅在IE8及以上版本中受支持。
完整代码示例
/***
* 获取系统的当前IE浏览器版本
* @returns
*/
function getExplorerInfo() {
var explorer = window.navigator.userAgent.toLowerCase();
//ie
if (explorer.indexOf("msie") >= 0) {
var ver = explorer.match(/msie ([\d.]+)/)[1];
return { type: "IE", version: ver };
}
}
function checkBrowser(){
var DEFAULT_VERSION = "8.0";
var ua = navigator.userAgent.toLowerCase();
var isIE = ua.indexOf("msie")>-1;
var safariVersion=null;
if(isIE){
safariVersion =getExplorerInfo().version;
if(safariVersion <= DEFAULT_VERSION ){
window.location.href= contextPath+"/Browser.jsp";
}else{
return;
}
}else{
return;
}
}至此,关于使用JavaScript检测IE8及以下浏览器版本并给出提示的函数代码介绍完毕。如需了解更多关于IE8以下浏览器版本的相关内容,请查阅本站往期文章或继续浏览后续文章。感谢大家的支持!