简体   繁体   English

使下拉菜单消失

[英]Make Dropdown menu Disappear

I have a code from W3schools, in which we get dropdown menu after clicked on a button. 我有一个来自W3schools的代码,单击一个按钮后,我们会在其中获得下拉菜单。

Dropdown menu don't disappear when we click anywhere else. 当我们单击其他任何地方时,下拉菜单不会消失。 I have surfed a bit but it seems confusing as am new to js. 我已经冲浪了一下,但是对于js来说似乎很令人困惑。

It would be much helpful if anyone could suggest how do we make it disappear? 如果有人可以建议我们如何使它消失,那将大有帮助。

Code Link 代码链接

Add the following code somewhere: 将以下代码添加到某处:

document.getElementById("myBtn").onblur = function() {
  document.getElementById("myDropdown").classList.remove("show");
};

The original code that you wrote triggers the addition or removal of the "show" class on the element of id "myBtn" only when this element itself is clicked: 您编写的原始代码仅在单击ID元素myBtn的元素本身时才触发该元素的添加或删除:

document.getElementById("myBtn").onclick = function() { document.getElementById("myDropdown").classList.toggle("show"); document.getElementById(“ myBtn”)。onclick = function(){document.getElementById(“ myDropdown”)。classList.toggle(“ show”); }; };

But it does nothing if you click outside, that's the role of the onblur event. 但是,如果您在外部单击,则不会执行任何操作,这就是onblur事件的作用。

<script>
// Get the button, and when the user clicks on it, execute myFunction
document.getElementById("myBtn").onclick = function() {
  myFunction()
};
document.getElementById("myBtn").onblur = function() {
  myFunction();
};

/* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}
</script>

Use this: 用这个:

 document.getElementById("myBtn").onblur = function(){ document.getElementById("myDropdown").classList.remove('show') }; 

"onBlur" is the Event for losing the focus “ onBlur”是失去焦点的活动

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

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