jQuery 单击页面上的任何其他内容时隐藏元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/893311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:03:49  来源:igfitidea点击:

hiding an element on click of anything else on the page

jquery

提问by Subliminal Hash

referring to Franek's question found hereI have one more question.

参考 Franek's question found here我还有一个问题。

The solution on the link above worked for me until I introduced another menu to my page. In this case, there are two menus next to each other. When I click on one of them, the relevant div is displayed showing possible options to select. Then, when I click on the document the div gets closed. But when I click on any other element it is still displayed.

上面链接上的解决方案对我有用,直到我在我的页面中引入了另一个菜单。在这种情况下,有两个相邻的菜单。当我单击其中之一时,会显示相关的 div,显示可能的选项。然后,当我单击文档时,div 将关闭。但是当我点击任何其他元素时,它仍然显示。

A solution for me would be to run the code to close the menu on any other element click as well as document click.

对我来说,一个解决方案是运行代码以关闭任何其他元素单击以及文档单击时的菜单。

How can I achieve this ?

我怎样才能做到这一点?

(menu: invisible div element that when clicked on its title becomes visible)

(菜单:不可见的 div 元素,单击其标题时会变为可见)

回答by Anh Do

This is slightly better, as it also check the parent(s) of the element being clicked:

这稍微好一点,因为它还会检查被单击元素的父元素:

$(document).click(function(e) {
    var target = e.target;

    if (!$(target).is('#menu') && !$(target).parents().is('#menu')) {
        $('#menu').hide();
    }
});

回答by coma

Clicking on every element but the menu that you want to hide right?

单击要隐藏的菜单以外的每个元素,对吗?

$(function() {
    $('*').click(function(e) {
        if(e.target.id != 'menu') {
            $('#menu').hide();
        }
    });
});

回答by iman64

my html code is

我的 html 代码是

<div class="filter-show">
    <ul style="display:none;">
        <li>menu 1</li>
        <li>menu 2</li>
        <li>menu 3</li>
    </ul>
</div>

and jquery code is

和 jquery 代码是

<script>
    $('html').click(function(event){
        if(!$(event.target).children().is('.filter-show > ul')){
            $(".filter-show > ul").fadeOut();
        }
    });
    $(".filter-show").click(function(){
        $(".filter-show > ul").fadeOut();
        $(this).children('ul').fadeIn();
    });
    $(".filter-show > ul").hover(function(){
        //
    },function(){
        $(".filter-show > ul").fadeOut();
    });
</script>