怎樣檢測瀏覽器是不是支撐某個偽類

怎樣檢測瀏覽器是不是支撐某個 CSS 偽類(比方 :focus-within

錯誤要領

@supports (div:focus-within) {}
CSS.supports('div:focus-within`);

此法檢測的是瀏覽器是不是支撐一個名為 div 的屬性,且值能夠為 focus-within,固然不支撐。。。

準確要領

function supportsPseudoClass(clazz) {
  const style = document.createElement('style');
  style.innerHTML = clazz + '{}';
  document.head.appendChild(style); // required, or style.sheet === null
  const result = style.sheet.cssRules.length === 1;
  style.remove(); // document.head.removeChild(style);
  return result;
}

supportsPseudoClass(':focus-within'); // => true

道理:假如 CSS 剖析器不認識某個偽類,CSS 會以為其整條劃定規矩都不正當,並將其疏忽。style.sheet.cssRules 只會寄存剖析勝利的劃定規矩,所以假如瀏覽器不認識這個偽類,就不會把這條劃定規矩存入 cssRules

同理,假如用到偽類的 polyfill,肯定不能將 polyfill 天生的類名和原始偽類連用。比方:

#div:focus-within, #div.focus-within {
}

假如瀏覽器不認識 :focus-within,CSS 剖析器會把整條劃定規矩悉數疏忽掉,起不到 polyfill 的結果。#div:focus-within, #div.focus-within 是一條選擇器

能夠這麼寫(scss):

@mixin div {
}

#div:focus-within {
  @include div;
}
#div.focus-within {
  @include div;
}

下一篇文章估計講講 :focus-within 的用途

    原文作者:CarterLi
    原文地址: https://segmentfault.com/a/1190000014814182
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞