Twitter

@carrielis 可以的

jQuery 实现多级下拉菜单

in Javascript // 9 Comments

在上篇文章 jQuery 实现下拉菜单方法 中写的代码仅仅是一级下拉菜单的情况,QiQiBoy 提了一下,想想是啊,因为自己平时博客中导航菜单都没有设置子菜单,就算本地测试的博客也只是设了一级菜单而已,已经成为惯性了。于是找了个时间再测试一下多级菜单的情况下,jQuery 的实现多级下拉菜单的方法。

相对前一篇的一级菜单,实现多级下拉菜单只要增加使用 .each() 方法。具体 jQuery 代码如下:

$(document).ready(function() {
    $("#nav li ul.children").hide();
        $("#nav li > ul.children").each(function() {
        $(this).parent("li").hover(function() {
            $(this).children(".children:not(:animated)").animate({opacity: "show", height: "show"}, "slow");
        }, function() {
            $(this).children(".children").animate({opacity: "hide", height: "hide"}, "100");
        });
    });
});

看看 Demo 最后一个菜单 Title5 的效果。

还可以做一下扩展,不要把下拉菜单限定在导航菜单上,让其他带有子菜单的菜单都能实现这效果:

$(document).ready(function() {
function showChild(menu) {
    menu.find("li ul").hide();
    menu.find("li > ul").each(function() {
        $(this).parent("li").hover(function() {
            $(this).children("ul:not(:animated)").animate({opacity: "show", height: "show"}, "slow");
        }, function() {
            $(this).children(".children").animate({opacity: "hide", height: "hide"}, "100");
        });
    });
}
//调用 showChild() 函数。
showChild($("#nav"));
});

比如想实现侧边栏的分类菜单下拉效果,加多一行类似 showChild($("#categories")); 的就行了,看你具体的 ID 或是类标签的设置了。

目前 IE6 和 IE7 下有问题。 IE 问题解决,其实不关 jQuery 代码问题,是我 CSS 代码没写好。

9 responses to jQuery 实现多级下拉菜单

Leave a Reply