gpt4 book ai didi

javascript - 单击时关闭下拉菜单

转载 作者:行者123 更新时间:2023-11-28 06:54:26 24 4
gpt4 key购买 nike

我想在单击文档中的任意位置时关闭下拉菜单,目前只有当我单击下拉菜单本身时它才会关闭。这是我目前拥有的 HTML 和 JQuery:

HTML:

<div class="user-menu">
<div id="dropdown" class="ddmenu">
<img src="#" class="user-menu-pic" alt="">
<span>Name Lastname</span>
<img src="images/dropdown-icon.png" class="right dropdown-icon" width="30" height="30" alt="">
<ul>
<li><a href="#">My Profile</a></li>
<li><a href="#">Change profile picture/background</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Change password</a></li>
<li><a href="#">Sign Out</a></li>
</ul>
</div>
</div>

Jquery:

      $('#dropdown').on('click', function (e) {
e.preventDefault();
if ($(this).hasClass('open')) {
$(this).removeClass('open');
$(this).children('ul').slideUp('fast');
} else {
$(this).addClass('open');
$(this).children('ul').slideDown('fast');
}
});

最佳答案

我认为您正在寻找这样的东西:

JSFiddle : DEMO

   $('#dropdown').on('click', function (e) {
e.preventDefault();
if ($(this).hasClass('open')) {
$(this).removeClass('open');
$(this).children('ul').slideUp('fast');
} else {
$(this).addClass('open');
$(this).children('ul').slideDown('fast');
}
});
$(document).mouseup(function (e) {
var container = $("#dropdown");

if (!container.is(e.target) // if the target of the click isn't the container...
&&
container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.children('ul').slideUp('fast');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="user-menu">
<div id="dropdown" class="ddmenu">
<img src="#" class="user-menu-pic" alt=""> <span>Name Lastname</span>

<img src="images/dropdown-icon.png" class="right dropdown-icon" width="30" height="30" alt="">
<ul>
<li><a href="#">My Profile</a>

</li>
<li><a href="#">Change profile picture/background</a>

</li>
<li><a href="#">Settings</a>

</li>
<li><a href="#">Change password</a>

</li>
<li><a href="#">Sign Out</a>

</li>
</ul>
</div>
</div>

Note : Actually it doesn't need two clicks, it's working with very first click. But you can see that when you click on Menu(very first time), so it is already open(i.e. Already slideDown) and does not have class open. So it executes the loop which returns false for hasClass("open"). Now in that loop we say menu to slideDown, which is already in the slideDown State.

如果您想要更好的解释,请帮我添加 class="ddmenu open"像这样的 html:<div id="dropdown" class="ddmenu open">然后再试一次。

关于javascript - 单击时关闭下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32671249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com