使用Javascript来检测Google Chrome以切换CSS [英] Using Javascript to detect Google Chrome to switch CSS
问题描述
我一直在玩不同的脚本,我发现一个除了Chrome之外的所有东西,这是我一直使用的代码不同的.CSS文件。我尝试只是将浏览器名称变成Chrome,但是没有工作。
I have been playing around with different scripts, I found one that works for everything but Chrome... this is the code I have been using to differ in .CSS files. I tried just makeing the Browser name into "Chrome" But that did not work.
if (browser == 'Firefox') {
document.write('<link rel="stylesheet" href="../component/fireFoxdefault.css" />');
}
if (browser == 'Safari') {
document.write('<'+'link rel="stylesheet" href="../component/default.css" />');
}
推荐答案
:
var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
资料来源: http://davidwalsh.name/detecting-google-chrome-javascript
更新(2015-07-20):
上述解决方案并不总是奏效。有关更可靠的解决方案,请参见此答案(见下文)。话虽如此,我会避免浏览器检测,并改用功能检测: / p>
The above solution does not always work. A more reliable solution can be found in this answer (see below). That being said, I would avoid browser detection and go with feature detection instead:
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
您可以包含专门用于chrome的css文件,例如:
You can include a css file specifically for chrome like this:
if (isChrome) {
document.write('<'+'link rel="stylesheet" href="../component/chromeDefault.css" />');
}
UPDATE(2014-07-29):
@gillesc有一个更优雅的建议检测Chrome,他在下面的评论中发布了,它也可以在这个问题。
@gillesc has a more elegant suggestion for detecting Chrome which he posted in a comment below and it can also be viewed on this question.
var isChrome = !!window.chrome
这篇关于使用Javascript来检测Google Chrome以切换CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!