[英]How to improve the code JS (Jquery)? A simple dropdown
How to edit code, to close the dropdown menu on second click.如何编辑代码,在第二次点击时关闭下拉菜单。 In page I have many dropdowns.在页面中我有很多下拉菜单。
$('.dropdown').on('click', function() { var active = 'active'; $(document).on('click', function() { $('.dropdown').removeClass(active); }); $('.dropdown').removeClass(active); $(this).toggleClass(active); return false; });
.dropdown { margin: 50px; width: 30px; height: 30px; position: relative; display: block; background: #333; cursor: pointer; } .dropdown ul { display: none; width: 100px; position: relative; bottom: -120%; left: -100%; } .dropdown.active ul { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="dropdown"> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> </div> <div class="dropdown"> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> </div>
As shown in example, just want to add to the menu from closing up when you click on the square.如示例所示,当您单击正方形时,只想从关闭状态添加到菜单中。
Just a simple line will suffice一条简单的线就足够了
$('.dropdown').on('click',function() {
$(this).find("ul").toggle();
});
Try this,试试这个,
$(document).on('click', function(e){
if($(e.target).parents('div.dropdown').length) {
return false;
}
$('.dropdown').toggleClass('active');
return false;
});
Updated for multiple dropdowns更新了多个下拉菜单
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.