jQuery切换菜单,在外部单击时隐藏下拉菜单内容

时间:2018-08-02 15:58:13

标签: javascript jquery drop-down-menu toggle

我已经使用jQuery创建了一个切换菜单,它工作正常,但是当在其外部单击时如何隐藏下拉菜单内容。请帮助我。谢谢 我正在建立一个产品评论和用户提交的帖子的网站。我需要一些帮助才能成功。

    <script>
    $(".dropbtn").click(function(e){
        $(".dropdown-content").toggle();
         e.preventDefault();
    });

    $(".dropbtn").click(function(e){
        $(this).hide();
         e.preventDefault();
    });
    $(".dropbtn").click(function(e){
        $(".dropbtnhide").show();
         e.preventDefault();
    });
    $(".dropbtnhide").click(function(e){
        $(".dropdown-content").hide();
         e.preventDefault();
    });
    $(".dropbtnhide").click(function(e){
        $(this).hide();
         e.preventDefault();
    });
    $(".dropbtnhide").click(function(e){
        $(".dropbtn").show();
         e.preventDefault();
    });
    $(".dropdown-content").click(function(e){
       e.preventDefault();
    });

    </script>

.dropbtnhide{display:none; position:relative;}
.dropbtn{display:inline-block; position:relative;}

<!-- begin snippet: js hide: false console: true babel: false -->
 <div class="celldisplay dropdown">
    <button  class="dropbtnhide "><i class="far fa-ellipsis-h"></i></button>
     <button class="dropbtn"> <i class="far fa-ellipsis-v"></i></button>
      <li><a></a>
       </li>
     </div> 

1 个答案:

答案 0 :(得分:0)

您可以通过为Element的{​​{1}}事件(window)添加事件监听器来检查click是否包含事件的目标。

演示:

Element.contains(event.target)
.dropbtn {
    background-color: #4CAF50;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

.dropdown {
    position: relative;
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

相关问题