[英]Jquery dropdown menu show/hide multiple
我一直在寻找很多问题/答案,但仍然无法解决我的问题。 因此,我有一个带有JS下拉菜单的菜单(单击时,没有悬停),但是如果我打开一个下拉菜单,然后单击第二个菜单,则会打开另一个下拉菜单,但上一个不会关闭。
单击菜单外部将关闭下拉菜单,这很好,但这还不够,我希望即使单击第二个下拉菜单也要关闭第一个下拉菜单!
<li><a onclick="myFunction_tools()" class="dropmenu" href="#">Tools</a></li>
<div id="myToolsDropdown" class="down">
<div>
Content here...
</div>
</div>
<li><a onclick="myFunction_forum()" class="dropmenu" href="#">Forum</a></li>
<div id="myForumDropdown" class="down">
<div>
Content here...
</div>
</div>
这是JS:
function myFunction_tools() {
document.getElementById("myToolsDropdown").classList.toggle("show");
}
function myFunction_forum() {
document.getElementById("myForumDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropmenu')) {
var dropdowns = document.getElementsByClassName("down");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
$(".down").click(function(e){
e.stopPropagation();
});
编辑2:
这是一个解决方案,应该适合您:
$(document).ready(function() { $('.dropmenu').click(function(e) { e.preventDefault(); $('.down').hide(); $(e.target).next('.down').show(); }); });
.down { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <li><a class="dropmenu" href="#">Tools</a> <div id="myToolsDropdown" class="down"> <div> Content here... </div> </div></li> <li><a class="dropmenu" href="#">Forum</a> <div id="myForumDropdown" class="down"> <div> Content here... </div> </div></li>
原版的:
单击下拉列表时,可以防止关闭所有下拉列表:
如果(!event.target.matches('。dropmenu'))
您必须更改条件,因此它仅与当前活动下拉列表匹配。 类似于“ if the event target matches the current active dropdown, prevent action
”。 您可以通过检查open
类来确定当前的活动下拉列表。
编辑:您可能只需要将条件更改为:
if (!event.target.matches('.dropmenu.active'))
因此,它会关闭所有未位于.dropmenu.active
点击的下拉菜单,然后触发点击。
另外,由于您似乎仍在使用jQuery,因此可以在整个脚本中使用jQuery来优化代码:
$(window).click(fucntion(event) {
var $target = $(event.target);
if(!$target.hasClass('show')){
$('.down').removeClass('show');
$target.addClass('show');
}
});
只需删除函数上一个下拉列表的show类。 例如:
function myFunction_tools() {
document.getElementById("myToolsDropdown").classList.toggle("show");
document.getElementById("myForumDropdown").classList.remove("show");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.