所有浏览器的CSS设置,但不是Chrome

时间:2015-08-30 15:06:08

标签: css google-chrome cross-browser

我在css中有这样的设置如下:

.row-height {
  height: 100% ;
}

我想为所有浏览器设置此设置,但不是Chrome。 有没有办法这样做。 金

2 个答案:

答案 0 :(得分:0)

您无法直接在CSS中检查特定浏览器,但您可以在JavaScript中的BODY元素上设置类,如下所示:

if (navigator.userAgent.match(/Chrome/))
  document.body.classList.add('chrome');

完成后,您可以为该特定浏览器添加CSS规则。就像在Chrome上使用自动高度而不是100%一样:

body.chrome .row-height { height: auto; } 

毋庸置疑,如果您不必执行此操作,这会增加开销并且容易以意想不到的方式破坏,这是最好的。对于你在CSS中直接面对的特殊问题,也许有不同的解决方法。

然而,有时需要使用这样的目标CSS来解决浏览器错误,所以不要感觉不好"如果你必须这样做。

答案 1 :(得分:0)

我能想到的最简单的方法是使用Javascript(1)检测浏览器,如果检测到Chrome则更改页面的CSS文件(2)。这个解决方案的缺点是你必须维护两个几乎相同的CSS文件,这在开发过程中可能相对比较麻烦。

所以,你的代码应该是这样的:

<link id="styleSheet" rel='stylesheet' href='style.css' type='text/css' media='all' />
<script>
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isChrome = !!window.chrome && !isOpera;
if(isChrome) {
     document.getElementById('styleSheet').href = "styleForChromeOnly.css";
}
</script>

或者,如果您不想在代码中使用一次性使用变量,或者您喜欢意大利面:

<link id="styleSheet" rel='stylesheet' href='style.css' type='text/css' media='all' />
<script>
if(!!window.chrome && !window.opera && navigator.userAgent.indexOf(' OPR/') >= 0) {
     document.getElementById('styleSheet').href = "styleForChromeOnly.css";
}
</script>

(1)How to detect Safari, Chrome, IE, Firefox and Opera browser?

(2)How can you change the attached CSS file with Javascript?