![](/img/trans.png)
[英]How to make dropdown menu disappear after a certain amount of time JavaScript
[英]Make Dropdown menu Disappear
我有一个来自W3schools的代码,单击一个按钮后,我们会在其中获得下拉菜单。
当我们单击其他任何地方时,下拉菜单不会消失。 我已经冲浪了一下,但是对于js来说似乎很令人困惑。
如果有人可以建议我们如何使它消失,那将大有帮助。
将以下代码添加到某处:
document.getElementById("myBtn").onblur = function() {
document.getElementById("myDropdown").classList.remove("show");
};
您编写的原始代码仅在单击ID元素myBtn的元素本身时才触发该元素的添加或删除:
document.getElementById(“ myBtn”)。onclick = function(){document.getElementById(“ myDropdown”)。classList.toggle(“ show”); };
但是,如果您在外部单击,则不会执行任何操作,这就是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>
用这个:
document.getElementById("myBtn").onblur = function(){ document.getElementById("myDropdown").classList.remove('show') };
“ onBlur”是失去焦点的活动
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.