簡體   English   中英

使下拉菜單消失

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM