[英]How to detect if browser support specified css pseudo-class?
如果規則無效,stylesheet.insertRule(rule, index)方法將拋出錯誤。 所以我們可以使用它。
var support_pseudo = function (){
var ss = document.styleSheets[0];
if(!ss){
var el = document.createElement('style');
document.head.appendChild(el);
ss = document.styleSheets[0];
document.head.removeChild(el);
}
return function (pseudo_class){
try{
if(!(/^:/).test(pseudo_class)){
pseudo_class = ':'+pseudo_class;
}
ss.insertRule('html'+pseudo_class+'{}',0);
ss.deleteRule(0);
return true;
}catch(e){
return false;
}
};
}();
//test
support_pseudo(':hover'); //true
support_pseudo(':before'); //true
support_pseudo(':hello'); //false
support_pseudo(':world'); //false
您可以簡單地檢查是否應用了偽類的樣式。
像這樣的東西: http : //jsfiddle.net/qPmT2/1/
對於仍在尋找此問題的快速解決方案的任何人,我根據此線程中的其他一些答案將一些內容匯總在一起。 我的目標是讓它簡潔。
function supportsSelector (selector) {
const style = document.createElement('style')
document.head.appendChild(style)
try {
style.sheet.insertRule(selector + '{}', 0)
} catch (e) {
return false
} finally {
document.head.removeChild(style)
}
return true
}
supportsSelector(':hover') // true
supportsSelector(':fake') // false
如果您可以使用 Javascript,則可以跳過檢測並直接使用 shim: Selectivizr
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.