如何通过单击任意位置来关闭javascript下拉菜单? [英] How to close javascript dropdown menu by clicking anywhere?

查看:44
本文介绍了如何通过单击任意位置来关闭javascript下拉菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个javascript下拉菜单.我从某个网站上获得了它,但工作正常,但问题是仅在单击菜单按钮时,下拉菜单才会关闭.即使单击页面上的其他任何位置,如何关闭下拉菜单.

Here is a javascript dropdown menu. I got it from some site it works fine but problem is the dropdown menu closes only when menu button is clicked. How can I make dropdown menu close even when I click any where else on page.

<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">ddm</button>
<div id="myDropdown" class="dropdown-content">
    <a href=""></a>
    <a href=""></a>
    <a href=""></a>
</div>
</div>

<script type="text/javascript">
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown");
var i;
for (i = 0; i < dropdowns.length; i++) {
  var openDropdown = dropdowns[i];
  if (openDropdown.classList.contains('show')) {
    openDropdown.classList.remove('show');
   }
  }
 }
}
</script>

推荐答案

尝试下面的代码,它应该可以工作

Try the code below, it should work

$(document).click(function(event) { 
    if(!$(event.target).closest('#myDropdown').length) {
        if($('#myDropdown').is(":visible")) {
            $('#myDropdown').hide()
        }
    }        
})

这篇关于如何通过单击任意位置来关闭javascript下拉菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆