这不是一个特别容易解决的问题(开箱即用),因为有多个元素依赖彼此的状态才能正常工作。我以前用 setTimeout 做过这个。
使用setTimeout来保持对一个变量的控制,该变量告诉每个悬停事件要做什么。只是把一个 jsFiddle 放在一起做你想要的(尽管我认为 mo 的上滑部分有问题):
http://jsfiddle.net/3vL3a/
和 JS / HTML:
$(document).ready(function () {
var menu = $('.menu')
var timeout = 0;
var hovering = false;
menu.hide();
$('#mainbutton')
.on("mouseenter", function () {
hovering = true;
// Open the menu
$('.menu')
.stop(true, true)
.slideDown(400);
if (timeout > 0) {
clearTimeout(timeout);
}
})
.on("mouseleave", function () {
resetHover();
});
$(".menu")
.on("mouseenter", function () {
// reset flag
hovering = true;
// reset timeout
startTimeout();
})
.on("mouseleave", function () {
// The timeout is needed incase you go back to the main menu
resetHover();
});
function startTimeout() {
// This method gives you 1 second to get your mouse to the sub-menu
timeout = setTimeout(function () {
closeMenu();
}, 1000);
};
function closeMenu() {
// Only close if not hovering
if (!hovering) {
$('.menu').stop(true, true).slideUp(400);
}
};
function resetHover() {
// Allow the menu to close if the flag isn't set by another event
hovering = false;
// Set the timeout
startTimeout();
};
});
HTML:
<div id="mainbutton">Hover over me!</div>
<div class="menu" style="background-color:red;">Test menu text
<br/>Test menu text
<br/>Test menu text
<br/>Test menu text
<br/>Test menu text
<br/>
</div>