问题
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>
回答1:
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);
});
});
回答2:
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
回答3:
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);
});
来源:https://stackoverflow.com/questions/12118292/jquery-slidedown-then-slideup-on-timer