Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

javascript - Test if a browser supports a CSS selector

Really simple: how do I most accurately test if a browser has support for a certain CSS selector?

I currently have some CSS code that makes the page a little more interactive by using the :checked selector in CSS, but I want to create a fallback script that does the same thing with JavaScript, but only if the user's browser has no support for the :checked selector.

My question is, how do I most accurately test if the user's browser supports a certain CSS selector?

Here is the code I'd like to use it on:

HTML:

<label class="coolbox">
    <input type="checkbox"/>
    <span>I want to eat some caek.</span>
</label>

CSS:

.coolbox input {display:none;}
.coolbox span::before {
    content: "";
    display:inline-block;
    width:10px;
    height:10px;
    margin-right:5px;
    border:1px solid black;
}
.coolbox:hover span::before {border:1px solid #555;}
.coolbox:active span::before {border:1px solid #999;}

.coolbox span::before {background-color:#F77;}
.coolbox input:checked + span::before {background-color:#4A4;}

Demo

PS: I'd prefer not to just use conditional comments, because I'd like to follow the standard of detecting features instead of browsers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use querySelector:

function testSelector(selector, node){
  var scope = document.createElement("div");
  scope.appendChild(node);

  try {
    return scope.querySelector(selector) !== null;
  } catch(e) { return false; }
}

You can test it like this:

var node = document.createElement("input");
node.type = 'checkbox';
node.checked = 'checked';

testSelector("input:checked", node); // === true

See this other question for more info on querySelector.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...