如何使用 JavaScript 检查浏览器是否支持焦点可见?

问题描述 投票:0回答:3

这个问题相当简单。我想检查浏览器是否支持焦点可见(

:focus-visible
)或不使用 JavaScript。我该怎么做?

javascript browser
3个回答
1
投票

console.log(selectorSupported(":focus-visible"))

function selectorSupported(selector){
  
  var support, link, sheet, doc = document,
      root = doc.documentElement,
      head = root.getElementsByTagName('head')[0],

      impl = doc.implementation || {
              hasFeature: function() {
                  return false;
              }
      },

  link = doc.createElement("style");
  link.type = 'text/css';

  (head || root).insertBefore(link, (head || root).firstChild);

  sheet = link.sheet || link.styleSheet;

  if (!(sheet && selector)) return false;

  support = impl.hasFeature('CSS2', '') ?
  
              function(selector) {
                  try {
                      sheet.insertRule(selector + '{ }', 0);
                      sheet.deleteRule(sheet.cssRules.length - 1);
                  } catch (e) {
                      return false;
                  }
                  return true;
                  
              } : function(selector) {
                
                  sheet.cssText = selector + ' { }';
                  return sheet.cssText.length !== 0 && !(/unknown/i).test(sheet.cssText) && sheet.cssText.indexOf(selector) === 0;
              };
   
  return support(selector);

};

所有功劳来自 Modernizr https://gist.github.com/paulirish/441842


1
投票

每个支持

:focus-visible
的浏览器也支持
CSS.supports()
API。

所以这应该有效:

window.CSS && CSS.supports && CSS.supports("selector(:focus-visible)")

或者在 ECMAScript 2020 中:

window.CSS?.supports?.("selector(:focus-visible)")

0
投票
try{document.querySelector(':focus-visible');}catch(e){console.log(':focus-visible not supported');};
© www.soinside.com 2019 - 2024. All rights reserved.