简体   繁体   中英

JQuery trigger hover won't work with :not(:hover)

I have a case very similar to this one: https://codepen.io/ianfarb/pen/EJunm

I'm trying to use jquery mouseenter to trigger a hover on the first image which has Id one.

window.setTimeout(function () {
    $('#one').trigger('mouseenter');
}, 2500)

However this doesn't appear to work, neither in my code nor in the one in the link above, as :not(:hover) style appears to always be applied. I've also tried with $().offset() to trigger redraw but that won't work either.

You could use a class to apply the hover styles (using opacity for example)

.image {
  opacity: .5;
}

.image:hover,
.image.is-hover {
  opacity: 1;
}

and then add it in your timeout (and make sure to cleanup the class on real hovers)

jQuery(function($) {
  function enter() {
    $(this).addClass('is-hover').siblings().removeClass('is-hover');
  }

  function leave() {
    $(this).removeClass('is-hover');
  }

  $('.image').hover(enter, leave);

  setTimeout(function() {
    enter.call($('.image:first-child'));
  }, 2500);
});

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