Jquery: How to add a delay to mouseleave so if someone accidentally hovers off the element unintentionally, it still stays open

故事扮演 提交于 2019-12-09 18:11:11

问题


THE hoverintent plugin is the opposite of what I need. I have a .popup that is triggered by .trigger, when i hover off of it, i want .popup to NOT fadeout for a few seconds, but if I hover off, then hover on again, cancel the fadeout that was going to happen and keep the .popup open.

Does anyone know how I would do this?

This DOESN'T work, but it was an idea:

 $('.trigger').hover(function(){
        $('.popup').fadeIn(600)
    }, function() {
        $('.popup').delay(2000, function(){
            if ($(this).blur() = true) {
                $('.popup').fadeOut(600)
            }
        });
    })

回答1:


the jQuery HoverIntent plugin is exactly what your looking for.

The timeout property will set the amount of time the mouse needs to be OUT of the area before the out function is called.

Quote from the hover intent website:

timeout: A simple delay, in milliseconds, before the "out" function is called. If the user mouses back over the element before the timeout has expired the "out" function will not be called (nor will the "over" function be called). This is primarily to protect against sloppy/human mousing trajectories that temporarily (and unintentionally) take the user off of the target element... giving them time to return. Default timeout: 0

To set it up...

$('.trigger').hoverIntent({
     over: startHover,
     out: endHover,
     timeout: 2000
});

Then define the functions to handle over and out

 function startHover(e){
    //your logic here
    $('.popup').fadeIn(600)
 }

 function endHover(){
     //your logic here
     $('.popup').fadeOut(600)
 }

EDIT:

You can also adjust the interval property to increase/decrease the amount of time for the startHover function to fire...the default is set to 100 milliseconds...you can set it to zero to fire off the popup as soon as the mouse enters the trigger area if youd like.




回答2:


Here's the simplest way to do it, without additional plugins:

$('.trigger').hover(function() {
    clearTimeout(this.timer);
    $('.popup').fadeIn(600);
}, function() {
    this.timer = setTimeout(function() { 
        if ($(this).blur() = true) { // off topic: you should to check this condition ;)
            $('.popup').fadeOut(600);
        }
    }, 2000);
});

setTimeout() and clearTimeout() are native JS functions of HTML DOM Window object since forever.




回答3:


You could try using the jquery hoverintent plugin.




回答4:


This works for me:

$(".triger").mouseenter(function() {
    $(this).find("popup").fadeIn();
}).mouseleave(function() {
    $(this).find("popup").delay(200).fadeOut();
});


来源:https://stackoverflow.com/questions/4831059/jquery-how-to-add-a-delay-to-mouseleave-so-if-someone-accidentally-hovers-off-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!