How to select a:hover that's not in a certain

2019-08-27 03:36发布

问题:

I would like to style a elements that are not in a certain id. For example, let's say this is my HTML:

<div id="boat">
   <a href="#">I'm in a boat! ☻</a>
</div>
<a href="#">☹</a>

Now, let's say I only want to style the a element that's not in a boat. I expected something similar to a:hover:not(#boat a) to work, but alas, it doesn't. Is there a way I can do what I want to do?

回答1:

When it comes to jQuery selectors a:hover will select all the a elements which have the CSS pseudo class :hover applied to it (i.e. a elements which are currently being hovered over with the mouse).

This is the selection process, and not the styling selection, to select the elements you are talking about, try this instead:

$('a:not(#boat a)')

DEMO: http://jsfiddle.net/marcuswhybrow/AMWhU/

If a hover jQuery effect is waht you are after the once you have made the selection just bind the event as usual:

$('a:not(#boat a)').hover(function() {});


回答2:

Links not within that div#id will have .closest('div#id').length === 0, and since 0 is false, you can select on the opposite of those as follows to style those links:

$('a').hover(function(e){
    if (!$(this).closest('div#boat').length) {
        // YOUR CODE HERE
    }
});

Here's an example.



回答3:

It looks like you can use a negating attribute selector ('!='). Given (mostly) your original html:

<script src="/Users/kburton/Downloads/jquery-1.4.4.min.js">
    </script>
<div id="boat">
  <a href="#">I'm in a boat!</a>
</div>
<div id='car'>
  <a href="#">I'm in a car!</a>
</div>
<a href="#">I'm not in the boat!</a>

At the javascript console, running:

$('[id!="boat"] > a')

Looks for all nodes that do not have the id 'boat', with an anchor child.