开发者

Detecting CSS Selector Support of Browser with jQuery

Normally, i'm using Modernizr for regular feature detection but it can't detect browser selector support (i.e: :nth-of-type() selector).

Is there a way to d开发者_开发百科etect selector support of browser with jQuery?


You are right that selecting an element with a jQuery selector will work even in browsers that do not support that selector in CSS.

However, you could apply a style with a CSS3 selector, and then select an element with jQuery to determine if that style has been applied.

For instance in CSS:

#myid > p {
  display: none;
}

and then in jQuery:

if ( $( '#myid > p' ).css('display') != 'none' ) {
 // blah
}

However be careful because .css() may not return what you expect. For instance if you apply a color like 'red', it will return rgb(255, 0, 0).

Sorry I know this isn't as perfect of a solution as Modernizr, but I hope it helps you in your situation.


You could try selecting something with that selector, if it returns 'NULL' either the browser does not support it, or there were no elements of that type

my suggestion is to use the selectors on something you know exists.


You shouldn't need jQuery for this - regular JavaScript will do you just fine:

function supportsSelector(selector){
  if(selector.indexOf(":") !== 0) {
    selector = ':'+selector;
  }
  try {
    var queryString = "body" + selector + ",body:not(" + selector + ")";
    return !!document.querySelector("body" + selector + ",body:not(" + selector + ")");
  } catch (e) {
    return false;
  }
}

console.log(supportsSelector("hover"));
console.log(supportsSelector(":hover"));
console.log(supportsSelector(":focus-within"));
console.log(supportsSelector("I made this up"));
console.log(supportsSelector(":not(.a, .b)"));

This should work in IE9 and up (need querySelector and :not support).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜