简体   繁体   中英

jQuery “hover state” - Test if element is no longer being hovered over

I know you can test, if a element is being hovered over by using:

$('.foo:hover').length > 0;

or on my case:

$(this).filter(':hover').length > 0;

Either will return a value of true if the element triggers the 'mouseenter' event. How ever i wish to test if an element is no longer being hovered over. I tried using:

!($(this).filter(':hover').length > 0;)

as well as

$(this).filter(':hover').length < 0;

But it is not giving me the desired result.

Example using above code

The context for this is a drop down menu i am working on.

Why not listen for the following:

  $('.box').on('mouseleave', function() {
    console.log($(this).filter(':hover').length > 0);
  });

Others have already mentioned mouseleave ; here's a snippet that's very similar to Robert's answer:

$('.box').on('mouseenter', function() {
  console.log($(this).filter(':hover').length > 0);
  $(this).on('mouseleave', function() {
    $(this).off('mouseleave');
    console.log('bye!');
  })
});

The difference is that it concerns itself solely with the original element in question, and kills itself once it fires.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM