HTML - 如何在不同的用户代理中显示不同的图像?
HTML - How to show different image in different user agents?
如果我使用 Chrome 我想显示 img1.jpg (<img src="img1.jpg" alt="my Chrome Image">
)。否则如果我用IE,我要显示img2.jpg(<img src="img2.jpg" alt="my IE Image">
)。可能吗?
提前致谢。
您可以使用以下函数执行此操作,然后只需使用 IF 语句设置该图像的属性。
function browsercheck() {
var userAgent = window.navigator.userAgent;
return (userAgent.indexOf("MSIE ") > 0 || !! userAgent.match(/Trident.*rv\:11\./));
}
var browser = browsercheck() ? 'IE' : 'Chrome';
if (browser == "IE")
{
//Set attribute
}
else if (browser == "Chrome")
{
//Set attribute
}
如果您需要了解确切的浏览器,请使用以下内容
navigator.browsercheck= (function(){
var ua= navigator.userAgent, tem,
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome'){
tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
return { 'browser': M[0], 'version': M[1] };
})();
然后您可以使用 navigator.browserInfo.browser
查询此信息以获取浏览器信息,或者如果您需要知道确切的版本,则可以使用 navigator.browserInfo.version
进行查询。
来源:Browser detection in JavaScript?
match = navigator.userAgent.match(/(chrome|safari|firefox|msie|opera|rv:11)\/?\s*([\d\.]+)/i);
match[1] 给出浏览器名称。另外"rv:11"表示IE11.
例如可以准备带前缀的图片,使用匹配值作为前缀:
myImg.src=match[1]+"-img1.jpg";
myImg.alt=match[1]+" Image";
如果我使用 Chrome 我想显示 img1.jpg (<img src="img1.jpg" alt="my Chrome Image">
)。否则如果我用IE,我要显示img2.jpg(<img src="img2.jpg" alt="my IE Image">
)。可能吗?
提前致谢。
您可以使用以下函数执行此操作,然后只需使用 IF 语句设置该图像的属性。
function browsercheck() {
var userAgent = window.navigator.userAgent;
return (userAgent.indexOf("MSIE ") > 0 || !! userAgent.match(/Trident.*rv\:11\./));
}
var browser = browsercheck() ? 'IE' : 'Chrome';
if (browser == "IE")
{
//Set attribute
}
else if (browser == "Chrome")
{
//Set attribute
}
如果您需要了解确切的浏览器,请使用以下内容
navigator.browsercheck= (function(){
var ua= navigator.userAgent, tem,
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome'){
tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
return { 'browser': M[0], 'version': M[1] };
})();
然后您可以使用 navigator.browserInfo.browser
查询此信息以获取浏览器信息,或者如果您需要知道确切的版本,则可以使用 navigator.browserInfo.version
进行查询。
来源:Browser detection in JavaScript?
match = navigator.userAgent.match(/(chrome|safari|firefox|msie|opera|rv:11)\/?\s*([\d\.]+)/i);
match[1] 给出浏览器名称。另外"rv:11"表示IE11.
例如可以准备带前缀的图片,使用匹配值作为前缀:
myImg.src=match[1]+"-img1.jpg";
myImg.alt=match[1]+" Image";