简体   繁体   English

HTML“下拉菜单” - 点击即可切换

[英]HTML “Dropdown Menu” - toggle on click

I created a "dropdown menu" in HTML that appears when you click on an element. 我在HTML中创建了一个“下拉菜单”,当您单击某个元素时会出现该菜单。 If you click on the element it will apply a class "selected" to the li which will cause the submenu to appear: 如果单击该元素,它将向li应用“选定”类,这将导致子菜单出现:

jsFiddle Example jsFiddle示例

I have code to right now that will show/hide the menu when clicking on the menu item. 我现在有代码,点击菜单项时会显示/隐藏菜单。 If a different menu is selected it will remove the selected class from it and toggle it on the one that was clicked: 如果选择了不同的菜单,它将从中删除所选的类,并在单击的菜单上切换它:

$("#menu").on("click", "li.dropdown", function(event) {
    event.preventDefault();
    event.stopPropagation();

    $(this).siblings(".dropdown").removeClass("selected");
    $(this).toggleClass("selected");
});

The problem is that the way I have this right now when I click on a child within the submenu it will toggle the menu and close it. 问题是,当我点击子菜单中的一个孩子时,我现在拥有它的方式将切换菜单并关闭它。

I also want to hide the menu when clicking anywhere else in the document. 我还想在单击文档中的任何其他位置时隐藏菜单。 This can be accomplished via: 这可以通过以下方式完成:

$(document).on("click", function(event) {
    $("#menu .dropdown").removeClass("selected");
});

1) How do I enable this toggle functionality without hiding the menu when the dropdown portion is clicked? 1)如何在单击下拉部分时隐藏菜单,如何启用此切换功能?

2) How do I hide the menu when clicking anywhere else on the document other than the menu / submenu itself? 2)如果单击菜单/子菜单本身以外的文档上的任何其他位置,如何隐藏菜单?

You seem to have answer #2 in an acceptable manner. 你似乎以可接受的方式回答#2。 To do #1: 做#1:

$('.submenu').click(function(e) {
    e.stopPropagation();
});​

jsFiddle example jsFiddle例子

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

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