在一些浏览器中,包括Chrome稳定版,你可以这样做:
h3 {
-webkit-filter: grayscale(1);
filter: grayscale(1);
}
你可能不知道,h1标签将以完全灰度的形式呈现。 历史往事总会重新上演.
无论如何 - 有人知道任何一种检测此功能的方法吗?
如果filter不起作用,我需要能够应用其他样式。
在一些浏览器中,包括Chrome稳定版,你可以这样做:
h3 {
-webkit-filter: grayscale(1);
filter: grayscale(1);
}
你可能不知道,h1标签将以完全灰度的形式呈现。 历史往事总会重新上演.
无论如何 - 有人知道任何一种检测此功能的方法吗?
如果filter不起作用,我需要能够应用其他样式。
filter
CSS 属性,但不是我们所有人都知道的方式(我指的是 CSS3 filter
)。CSS3 filter
,我们应该使用一些 浏览器检测。如我在我的评论中所提到的。documentMode
属性,并将其与我们简单的特性检测结合起来,我们可以排除 IE 中所谓的假阳性。function css3FilterFeatureDetect(enableWebkit) {
//As I mentioned in my comments, the only render engine which truly supports
//CSS3 filter is webkit. so here we fill webkit detection arg with its default
if(enableWebkit === undefined) {
enableWebkit = false;
}
//creating an element dynamically
el = document.createElement('div');
//adding filter-blur property to it
el.style.cssText = (enableWebkit?'-webkit-':'') + 'filter: blur(2px)';
//checking whether the style is computed or ignored
//And this is not because I don't understand the !! operator
//This is because !! is so obscure for learning purposes! :D
test1 = (el.style.length != 0);
//checking for false positives of IE
//I prefer Modernizr's smart method of browser detection
test2 = (
document.documentMode === undefined //non-IE browsers, including ancient IEs
|| document.documentMode > 9 //IE compatibility moe
);
//combining test results
return test1 && test2;
}
if(document.body.style.webkitFilter !== undefined)
或者
if(document.body.style.filter !== undefined)
额外信息:
如果只需要简单的功能检测,请使用上面的代码。要查看支持的功能列表,请参见此处:
想在Chrome中实时演示filter
,请查看此处:
还有两个资源供您参考:
当我写这篇答案时,您必须使用webkit
供应商前缀才能使其正常工作。
.filter
被定义但无法使用似乎非常奇怪和不可靠 - 这有点违背了特性测试的意义,如果它是错误的。 - Alan H.filter
CSS属性,用于不同的目的,而新标准则替换了它。也许Chrome一直支持filter
是为了与IE兼容,这就解释了为什么它被定义了,但请放心,一旦标准化,它将被替换为与webkitFilter
相同的东西。不幸的是,这确实使功能检测变得复杂 - 你如何以未来为导向的方式检测filter
的存在,以免对IE产生误报? - AshleysBrainfilter
,但是以非标准的方式,那么为什么要寻找功能检测呢?还不如使用浏览器检测! - Sepehr建议以下操作:
var supportsFilters = (function() {
var filterEl = document.createElement('div');
filterEl.style.cssText = 'filter:blur(2px)';
return filterEl.style.length != 0 && (document.documentMode === undefined || document.documentMode > 9);
})();
@support
来有条件地应用样式。请注意,@support
的浏览器支持是很好但不完美的。以下是一篇不错的文章,其中解释了如何使用几个示例:https://iamsteve.me/blog/entry/feature-detection-with-css
例如,你可以像这样做(查看实际效果):@supports (filter: grayscale(1)) or (-webkit-filter: grayscale(1)) {
h3 {
-webkit-filter: grayscale(1);
filter: grayscale(1);
}
}
@supports not (filter: grayscale(1)) and not not (-webkit-filter: grayscale(1)) {
h3 {
color: #808080;
}
}
@support
但不支持CSS filter
的浏览器数量一定很少...可能只有Opera Mini和一些嵌入式浏览器。 - Alan H.@support
。 - Alan H.
filter
内部的不同样式,还是filter
本身? - Sepehr