jQuery slideDown & then slideUp on timer

2019-04-16 02:11发布

I have a simple .slideDown function:

$globalTabs.find('.seeMore a').live("click", function(){
     $globalTabs.find(".allTabs").slideDown('slow');
 });

When a user clicks on an <a> in .allTabs ,.allTabs does a .slideUp.

What I want to do, is if a user has not clicked anything in .allTabs and the mouse is no longer within .allTabs, then a timer initiates to wait x amount of time and then do the .slideUp. Additionally, if the mouse enters .allTabs again before the .slideUp triggers - then the timer is stopped and resets when the mouse is moved outside of .allTabs

Not sure how to approach. Any help would be appreciated.

base markup:

<div class="allTabs">
   <a href="#">link 1</a>
   <a href="#">link 2</a>
   <a href="#">link 3</a>
   <a href="#">link 4</a>
</div>

and:

<li class="seeMore"><a href="#">see more</a></li>

3条回答
Root(大扎)
2楼-- · 2019-04-16 02:52

Set a timer to do the slideup in the callback of the slidedown and on mouseout of .allTabs. Cancel the timer on mouseover on .allTabs.

var $timer;

function hideAllTabs() {
    $globalTabs.find(".allTabs").slideUp('slow');
}
$globalTabs.find('.seeMore a').live("click", function(){
    $globalTabs.find(".allTabs").slideDown('slow', function() {
        $timer = setTimeout(hideAllTabs, 1000);
    });
});
$globalTabs.find(".allTabs").live("mouseout",function() {
    $timer = setTimeout(hideAllTabs, 1000);
});
$globalTabs.find(".allTabs").live("mouseover",function() {
    clearTimeout($timer);
});

查看更多
\"骚年 ilove
3楼-- · 2019-04-16 02:55

Try this way:

$(function() {
    var $allTabs = $globalTabs.find(".allTabs");
    var timer;
    $globalTabs.find('.seeMore a').live("click", function(){
        $allTabs.slideDown('slow');
    });
    $allTabs.mouseout(function(){
        timer = setTimeout(function() {$allTabs.slideUp()}, 3000);
    });
    $allTabs.mouseover(function() {
        clearTimeout(timer);
    });
});
查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-16 02:57

You can use setTimeout and clearTimeout functions, note that live method has been deprecated, you can use the on method instead.

var timeout;

$(document).on({
    mouseenter: function(){
        clearTimeout(timeout)
    },
    mouseleave: function(){
        var $this = $(this)    
        timeout = setTimeout(function(){
           $this.slideUp('slow')         
        }, 500)
    },
}, ".allTabs")

Fiddle

Update:

var timeout;

$(document).delegate(".allTabs", "mouseenter", function() {
    clearTimeout(timeout)
})

$(document).delegate(".allTabs", "mouseleave", function() {
    var $this = $(this)
    timeout = setTimeout(function() {
        $this.slideUp('slow')
    }, 1000)
})

Fiddle

查看更多
登录 后发表回答