简体   繁体   English

特征检测的最佳方法:focus-within 伪类

[英]Best way to feature detect :focus-within pseudo-class

I can't find any syntax using @supports that works with pseudo-class, except for not which is very specific to that pseudo-class.我找不到任何使用 @supports 的语法与伪类一起使用,除了not非常特定于该伪类的语法。

What is the best way to detect if a browser supports focus-within, as I don't want to write a lot of browser hacks that will change in a few versions?检测浏览器是否支持焦点内的最佳方法是什么,因为我不想编写很多会在几个版本中改变的浏览器黑客? I'm using Node and npm, but don't want to import a whole package for it (usually not the best way to handle things).我正在使用 Node 和 npm,但不想为它导入整个 package(通常不是处理事情的最佳方式)。

Trying to read the browser version string or use today's browser parsing hacks isn't a good idea because it will be difficult to maintain when browsers do start supporting a feature, so I'm looking for a feature detection method besides @supports.尝试读取浏览器版本字符串或使用当今的浏览器解析黑客不是一个好主意,因为当浏览器开始支持某个功能时将很难维护,因此我正在寻找除@supports 之外的功能检测方法。 Is there a way to determine this in javascript?有没有办法在 javascript 中确定这一点?

Since it's a pseudo class and therefor part of selectors, you would need the @supports selector (…) syntax here - but browser support for that specifically is not very good yet.由于它是一个伪 class 并且因此是选择器的一部分,因此您需要在此处使用@supports selector (…)语法 - 但浏览器对此的具体支持还不是很好。 (Basically just Firefox as of now.) (到目前为止,基本上只有 Firefox。)

With some quick research I came across https://github.com/Modernizr/Modernizr/issues/2270 though - part of a discussion regarding implementing a test for this in the Modernizr library.通过一些快速研究,我发现了https://github.com/Modernizr/Modernizr/issues/2270 - 这是关于在 Modernizr 库中实施测试的讨论的一部分。 User patrickkettner suggests the following JavaScript solution:用户 patrickkettner 建议以下 JavaScript 解决方案:

Actually.实际上。 There is a simpler way.有一个更简单的方法。

document.querySelector throws on invalid selectors. document.querySelector抛出无效的选择器。 You can just call document.querySelector(':focus-within') within a try-catch, if it doesn't throw it should be supported.您可以在 try-catch 中调用document.querySelector(':focus-within') ,如果它不抛出它应该得到支持。 We may find a browser that gives a false result, in which case we would need to actually test the style.我们可能会找到一个给出错误结果的浏览器,在这种情况下,我们需要实际测试样式。 However, in the mean time since it is a modern feature, we should be good with just that sniff test for now然而,与此同时,由于它是一个现代功能,我们现在应该很好地进行嗅探测试

Since this basic test still seems to be all Modernizer is doing in that regard currently ( https://github.com/Modernizr/Modernizr/blob/master/feature-detects/css/focuswithin.js ), I guess this should be safe to use.由于这个基本测试似乎仍然是 Modernizer 目前在这方面所做的一切( https://github.com/Modernizr/Modernizr/blob/master/feature-detects/css/focuswithin.js ),我想这应该是安全的使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM