使用jQuery创建一个简单的子菜单下拉菜单 [英] Creating a simple submenu drop down using jQuery

查看:140
本文介绍了使用jQuery创建一个简单的子菜单下拉菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的目标目标的示例:

我不喜欢我必须用类来装饰li元素,以便正确触发该事件.如果我有多个嵌套类别下拉菜单,会发生什么情况?事情变得一团糟!

I don't like I have to decorate a li element with a class in order to correctly fire the event. What happens if I have more than one nested category drop down? Things get messy quick!

离开事件捕获区域后,如果没有关闭该选项,我似乎也无法选择.

I also can't seem to be able to select an option without it closing as soon as I leave the event capture area.

关于如何构建精心制作的下拉导航菜单的任何建议?

Any suggestions on how to build a well crafted, drop down navigation menu?

推荐答案

您实际上不需要任何巧妙使用选择器的类:P

You don't really need any classes with some clever usage of the selectors :P

我用示例设置了小提琴,下面是代码:

I set up a fiddle with an example, here's the code:

HTML:

<nav>
    <ul>
        <li><a href="#">HOME</a></li>
        <li>
            <a href="#">OFFERS</a>
            <ul>
                <li>
                    <a href="#">NEW</a>
                    <ul>
                        <li>YAY!</li>
                    </ul>
                </li>
            </ul>
        </li>
        <li><a href="#">SETTINGS</a></li>
        <li><a href="#">TV's</a></li>
        <li><a href="#">COMPUTERS</a></li>
        <li><a href="#">RICE</a></li>
    </ul>
</nav>​

如您所见,不需要一个类/id:P元素"OFFERS"是唯一一个带有下拉菜单的元素,并且在该菜单内,元素"NEW"具有另一个菜单.

As you see, not a single class/id was needed :P The element "OFFERS" is the only one with a drop-down menu, and inside that menu, the element "NEW" has another one.

CSS:

li > ul { display: none; }
li li { margin-left: 10px; }

第一种样式很重要.首先,我们希望隐藏子菜单.另一种样式只是为了清楚起见.

The first style is the important one. At first, we want our submenus to be hidden. The other style is just for the sake of clarity.

jQuery:

$("nav ul li").hover(function(){
    if ($("> ul", this).length > 0) {
        $("> ul", this).show();
    }
}, function(){
    if ($("> ul", this).length > 0) {
        $("> ul", this).hide();
    }
});​

是的,就这么简单:)当我们hover菜单元素时,我们检查它是否有任何ul直接子元素,如果有,我们将其显示出来.当我们离开菜单元素时,我们再次检查它是否有任何ul直接子元素,如果有,我们将其隐藏.

Yup, as simple as that :) When we hover a menu element, we check if it has any ul direct children, if it does, we show them. When we leave the menu element, we check again if it has any ul direct children, and if it does, we hide them.

当然,您需要对此进行样式设置,并确保清除任何li中的所有浮点.

Of course, you'll need to style this up, and make sure your clear any float inside any li.

这篇关于使用jQuery创建一个简单的子菜单下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆