Make Dropdown菜单消失

时间:2017-07-05 14:55:32

标签: javascript dom

我有W3schools的代码,点击按钮后我们会得到下拉菜单。

当我们点击其他地方时,下拉菜单不会消失。 我有点冲浪,但它似乎令人困惑,因为我是js的新手。

如果有人能建议我们如何让它消失,那会很有帮助吗?

Code Link

3 个答案:

答案 0 :(得分:2)

在某处添加以下代码:

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

您编写的原始代码仅在单击此元素本身时触发在“myBtn”元素上添加或删除“show”类:

  

document.getElementById(“myBtn”)。onclick = function(){       的document.getElementById( “myDropdown”)classList.toggle( “播放”)。     };

但如果你点击外面没有任何作用,那就是onblur事件的作用。

答案 1 :(得分:1)

<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>

答案 2 :(得分:1)

使用此:

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

&#34;的onblur&#34;是失去焦点的事件

相关问题