简体   繁体   English

单击时如何停止下拉菜单子向上滑动

[英]how to stop dropdown menu child sliding up when clicked

I am attempting to make a dropdown menu that when clicked stays down but also, when clicking anywhere within the dropdown area, it will not slide up. 我正在尝试创建一个下拉菜单,当单击该菜单时,该菜单会保持向下,但在下拉区域内的任何位置单击时,该菜单都不会向上滑动。 Only when clicked elsewhere on the page should it disappear. 仅当单击页面上的其他位置时,它才会消失。

I am struggling to make this happen though. 我正在努力做到这一点。 You can see what I am doing here: 您可以在这里看到我在做什么:

HTML HTML

<nav id="moo">
<ul>
<li>Item 1 <i>o</i>
<div class="dropdown">
        <ul>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
        </ul>
    </div>
</li>
<li>Item 1 <i>o</i>
    <div class="dropdown">
        <ul>
            <li>Item 7</li>
            <li>Item 8</li>
            <li>Item 9</li>
        </ul>
    </div>
</li>
</ul>
</nav>

CSS CSS

ul { padding: 0px; margin: 0px; }
li { display: inline; }
nav li { position: relative; }
nav i { cursor: pointer; font-weight: bold; background-color: red;padding: 5px; }
.dropdown { display: none; position: absolute; border:1px solid #ccc; padding: 10px; }  
.dropdown li {
display: block;
}

SCRIPT 脚本

$('nav li').click(function () {
var $childDropdown = $(this).find('.dropdown');

if ($childDropdown.is(':visible')) {
    $('.dropdown').slideUp(300);
} else {
    $('.dropdown').slideUp(300);
    $childDropdown.slideDown(300);
}
});

/* Anything that gets to the document
will hide the dropdown */
$(document).click(function(){
$(".dropdown").hide();
});

/* Clicks within the dropdown won't make
it past the dropdown itself */
$("nav").click(function(e){
e.stopPropagation();
});

Here is fiddle version: 这是小提琴版本:

http://jsfiddle.net/susannalarsen/buNq9/ http://jsfiddle.net/susannalarsen/buNq9/

You will need to work with the event target property and traverse up its parents to find out what element has triggered the event. 您将需要使用事件目标属性,并遍历其父项,以找出触发事件的元素。 if it's an element inside ".dropdown" class, then no sliding-up should be applied, otherwise close dropdown. 如果它是“ .dropdown”类中的一个元素,则不应应用任何向上滑动,否则请关闭下拉菜单。

example

$('nav > ul > li').click(function (e) {
var $childDropdown = $(this).find('.dropdown');

if ($childDropdown.is(':visible')) {

    var target = $(e.target);
    if (!$(target).parents(".dropdown").length) {
        $('.dropdown').slideUp(300);
    }    

} ... } ...

Notice that i changed the selection in $('nav > ul > li'), which will apply only to the LI elements of the upper level. 注意,我在$('nav> ul> li')中更改了选择,该选择仅适用于上级的LI元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM