And*_*ren 19 javascript css css3 css-variables browser-feature-detection
最新版本的Firefox支持CSS变量,但Chrome,IE和其他浏览器的数量都没有.应该可以访问DOM节点或编写一个返回浏览器是否支持此功能的方法,但是我无法找到当前能够执行此操作的任何内容.我需要的是一个解决方案,如果浏览器不支持该功能,我可以将其用作运行代码的条件,例如:
if (!browserCanUseCssVariables()) {
// Do stuff...
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*lly 37
我们可以这样做CSS.supports.这是CSS @supports规则的JavaScript实现,目前可在Firefox,Chrome,Opera和Android浏览器中使用(请参阅我可以使用...).
该
CSS.supports()浏览器是否支持给定的CSS功能,或不静态方法返回一个布尔值,指示.
- Mozilla开发者网络
有了这个,我们可以简单地说:
CSS.supports('color', 'var(--fake-var)');
Run Code Online (Sandbox Code Playgroud)
结果将是true浏览器支持CSS变量,false如果不支持.
(您可能认为这样CSS.supports('--fake-var', 0)可行,但正如对此答案的评论中所述,Safari似乎有一个错误,使其失败.)
在Firefox上,此代码段将生成绿色背景,因为我们的CSS.supports调用返回true.在不支持CSS变量的浏览器中,背景将为红色.
var body = document.getElementsByTagName('body')[0];
if (window.CSS && CSS.supports('color', 'var(--fake-var)')) {
body.style.background = 'green';
} else {
body.style.background = 'red';
}Run Code Online (Sandbox Code Playgroud)
请注意,这里我还添加了检查以查看是否window.CSS存在 - 这将防止在不支持此JavaScript实现的浏览器中抛出错误并将其视为false一样.(CSS.supports在引入CSS全球的同时推出,所以也没有必要检查它.)
browserCanUseCssVariables()功能在您的情况下,我们可以browserCanUseCssVariables()通过简单地执行相同的逻辑来创建函数.以下代码段将提醒true或false取决于支持.
function browserCanUseCssVariables() {
return window.CSS && CSS.supports('color', 'var(--fake-var)');
}
if (browserCanUseCssVariables()) {
alert('Your browser supports CSS Variables!');
} else {
alert('Your browser does not support CSS Variables and/or CSS.supports. :-(');
}Run Code Online (Sandbox Code Playgroud)



使用CSS变量设置CSS样式并使用Javascript进行校对,getComputedStyle()如果设置了...
getComputedStyle()在许多浏览器中都支持:http://caniuse.com/#feat=getcomputedstyle
HTML
<div class="css-variable-test"></div>
Run Code Online (Sandbox Code Playgroud)
CSS
:root {
--main-bg-color: rgb(1, 2, 3); /* or something else */
}
.css-variable-test {
display: none;
background-color: var(--main-bg-color);
}
Run Code Online (Sandbox Code Playgroud)
JavaScript的
var computedStyle = getComputedStyle(document.getElementsByClassName('css-variable-test')[0], null);
if (computedStyle.backgroundColor == "rgb(1, 2, 3)") { // or something else
alert('CSS variables support');
}
Run Code Online (Sandbox Code Playgroud)
FIDDLE:http://jsfiddle.net/g0naedLh/6/
您不需要Javascript来检测浏览器是否支持自定义属性,除非Do stuff...是Javascript本身.既然你正在检测支持的东西是CSS,我认为你想要做的东西都是CSS.因此,如果有一种方法可以从这个特定问题中删除JS,我建议使用Feature Queries.
@supports (display: var(--prop)) {
h1 { font-weight: normal; }
/* all the css, even without var() */
}
Run Code Online (Sandbox Code Playgroud)
功能查询测试对语法的支持.你不必查询display; 你可以使用你想要的任何财产.同样,--prop甚至不需要存在的价值.您所做的只是检查浏览器是否知道如何阅读该语法.
(我之所以选择,display是因为几乎每个浏览器都支持它.如果你使用flex-wrap或者其他东西,你将不会抓住那些支持自定义道具但不支持flexbox的浏览器.)
旁注:我更喜欢将它们称为自定义属性,因为它正是它们的原因:作者定义的属性.是的,您可以将它们用作变量,但它们作为属性有一些优点,例如DOM继承:
body { --color-heading: green; }
article { --color-heading: blue; }
h1 { color: var(--color-heading); } /* no need for descendant selectors */
Run Code Online (Sandbox Code Playgroud)