单击除div以外的主体时隐藏div [英] hide a div on clicking the body other than the div

查看:96
本文介绍了单击除div以外的主体时隐藏div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我单击除div之外的页面正文时,我想隐藏所有div的隐藏物. 我的div是

I want to hide all div's hide when clicked on the body of the page other than the div. my div is

<div id="settingsBoxExpand">
                    <div id="settings1" class="settingsBoxExpandItem" style="padding:3px;border-bottom:1px solid #dddddd">My Account</div>
                    <div id="settings2" class="settingsBoxExpandItem" style="padding:3px;border-bottom:1px solid #dddddd">Preferences</div>
                    <div id="settings3" class="settingsBoxExpandItem" style="padding:3px;">Logout</div>
                </div>

,然后单击settingsBoxExpand div,将向下滑动. 我需要在单击settingsBoxExpand div以外的其他任何位置时将其隐藏. 我还有3个类似的div. 尝试过

and on clicking the settingsBoxExpand div in will be slides down. i need to hide this on clicking any other position other than settingsBoxExpand div. i have 3 more similar div's. tried

$('body:not(#settingsBoxExpand)').click(function(){
            $("#settingsBoxExpand").hide();
        });

,但不起作用. 不"对我不起作用. 预先感谢.

but its not working. "not" doesn't works for me. thanks in advance.

推荐答案

您需要设置正文(或文档)以隐藏单击框,并阻止div上的click事件冒泡DOM并触发正文点击事件:

You need to setup the body (or document) to hide the box on click and stop the click events on the div from bubbling up the DOM and triggering a body click event:

$('body').click(function(){
    $("#settingsBoxExpand").hide();
});

$('#settingsBoxExpand').click(function(event) {
    event.stopPropagation();
});

通过将.hide()放置为正文的单击处理程序的一部分,当单击事件使DOM冒起并到达正文时,它将隐藏div.使用.stopPropagation,您可以防止事件到达主体.

By placing the .hide() as part of the click handler for the body, it will hide the div when click events bubble up the DOM and reach the body. With .stopPropagation you prevent the event from reaching the body.

事件捕获和冒泡对于了解更高级的事件处理非常重要.如果您有兴趣的话,还可以阅读以下内容:

Event capturing and bubbling is important to understand with more advanced event handling; here's a little more reading if you're interested:

http://www.quirksmode.org/js/events_order.html

这篇关于单击除div以外的主体时隐藏div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆