jquery下拉菜单
jQuery 下拉菜单实现方法
使用 jQuery 实现下拉菜单可以通过监听鼠标事件或点击事件来控制菜单的显示与隐藏。以下是几种常见的实现方式:
基础实现(鼠标悬停触发)

$(document).ready(function() {
$('.dropdown').hover(
function() {
$(this).find('.dropdown-menu').stop(true, true).slideDown(200);
},
function() {
$(this).find('.dropdown-menu').stop(true, true).slideUp(200);
}
);
});
点击触发下拉菜单
$(document).ready(function() {
$('.dropdown-toggle').click(function() {
$(this).next('.dropdown-menu').toggle();
});
});
点击外部区域关闭菜单

$(document).ready(function() {
$('.dropdown-toggle').click(function(e) {
e.stopPropagation();
$(this).next('.dropdown-menu').toggle();
});
$(document).click(function() {
$('.dropdown-menu').hide();
});
});
HTML 结构示例
<div class="dropdown">
<button class="dropdown-toggle">菜单</button>
<ul class="dropdown-menu">
<li><a href="#">选项1</a></li>
<li><a href="#">选项2</a></li>
<li><a href="#">选项3</a></li>
</ul>
</div>
CSS 样式建议
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-menu {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-menu li {
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-menu li:hover {
background-color: #f1f1f1;
}
动画效果增强
使用 jQuery 的动画方法可以为下拉菜单添加平滑的显示/隐藏效果:
$(document).ready(function() {
$('.dropdown-toggle').click(function() {
$(this).next('.dropdown-menu').stop(true, true).fadeToggle(300);
});
});
多级下拉菜单实现
对于多级嵌套的下拉菜单,可以递归处理子菜单:
$(document).ready(function() {
$('.dropdown').hover(function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
$(this).find('.dropdown-submenu').find('.dropdown-menu').hide();
}, function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideUp(300);
});
$('.dropdown-submenu > a').click(function() {
$(this).next('.dropdown-menu').stop(true, true).slideToggle(300);
return false;
});
});






