17

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

h3 {
  -webkit-filter: grayscale(1);
  filter: grayscale(1);
}

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

无论如何 - 有没有人知道对此进行特征检测的任何方法?

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

4

3 回答 3

19

所谓的更新答案:

正如 OP 提到的一个好点,我正在更新答案,但这与我之前的答案没有任何相关或矛盾,这只是浏览器检测。

Alan 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;
}

原始的 Modernizr 源


if(document.body.style.webkitFilter !== undefined)

或者

if(document.body.style.filter !== undefined)

额外的信息:

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

对于filters 在 Chrome 中的现场演示,请看这里:

还有 2 个资源供您使用:

在我写这个答案时,您必须使用webkit供应商前缀才能使其工作。

于 2012-06-15T08:38:11.287 回答
2

以@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);
})();
于 2019-02-27T21:15:08.357 回答
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;
  }
}
于 2019-05-27T05:12:49.287 回答