如何检测CSS过滤器?

Ala*_* H. 16 css browser-feature-detection

在某些浏览器中,包括Chrome稳定版,您可以这样做:

h3 {
  -webkit-filter: grayscale(1);
  filter: grayscale(1);
}
Run Code Online (Sandbox Code Playgroud)

你不知道吗,h1将完全以灰度渲染.旧的一切都是新的.

无论如何 - 有没有人知道任何特征检测方法?

如果fil filter不起作用,我需要能够应用其他样式.

Sep*_*ehr 19

所谓的UPDATED答案:

由于OP提到了一个好点,我正在更新答案,但这与我之前的答案没有任何相关或相反,这只是一个浏览器检测.

艾伦·H在第10届之前提到了IE.版本,支持filtercss属性,但不是我们都知道的方式(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;
}
Run Code Online (Sandbox Code Playgroud)

原始的Modernizr来源


if(document.body.style.webkitFilter !== undefined)
Run Code Online (Sandbox Code Playgroud)

要么

if(document.body.style.filter !== undefined)
Run Code Online (Sandbox Code Playgroud)

额外的信息:

对于简单的特征检测,请使用上面的代码.有关支持的功能列表,请查看此处:

filter在Chrome中进行现场演示,请在此处查看:

还有2个资源供您使用:

在我写这个答案时,你必须使用webkit供应商前缀才能使它工作.


F L*_*has 2

您现在可以使用 CSS 的内置功能@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;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 更重要的是,旁边还有一个 JS 选项:[Mozilla 文档](https://developer.mozilla.org/en-US/docs/Web/API/CSS/supports) (2认同)