jQuery点击div外面应该隐藏div,点击子div不应该隐藏

时间:2015-01-14 05:31:33

标签: javascript jquery html css

我有像这样的HTML标记

<div class="outside">
    <div class="wrapper">
        <div class="content-wrap">
            <div class="content">
                <div class="content-container">
                    <div class="text">
                        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

我希望当在content-wrap div的外部单击鼠标时,内容包装div应该隐藏。在我的标记中,您可以看到我在内容换行之前使用了两个名为outside和wrapper的div。但实际上我在内容包装之前有很多div。如果点击了内容包装的任何子div,那么div不应该隐藏。有人能告诉我怎么做吗?任何帮助和建议都会非常明显。 这是fiddle link

4 个答案:

答案 0 :(得分:0)

您可以在stopPropagation()的点击事件上致电.content-wrap,以防止动作冒泡:

$('div.content-wrap').click(function(e) {
    e.stopPropagation()
});

$("body").click(function(){
   $(".content-wrap").fadeOut(); 
});

FIDDLE

答案 1 :(得分:0)

为什么不选择内容类并隐藏它?

jQuery(document).ready(function() {
    jQuery('.content').click(function() {
        $( ".content" ).hide( "slow", function() {
            alert( "Animation complete." );
          });
    });
});

答案 2 :(得分:0)

JS代码:

重复点击功能是因为.parents()过滤器参数只允许一个CSS选择器。

jQuery(document).ready(function() {
    jQuery('div.content-wrap').parents('.outside').click(function(){
        $(this).find('div.content-wrap').hide();
    }).end().parents('.wrapper').click(function(){
        $(this).children('div.content-wrap').hide();
    });        
});

小提琴: http://jsfiddle.net/f2p23vsq/14/

答案 3 :(得分:0)

您可以使用

隐藏文字
jQuery(document).ready(function () {
    $("html").click(function () {
        jQuery(".content-wrap").fadeOut();
    });
    $(".content-wrap").click(function () {
        alert("click");
        return false;
    });
});

jsfiddle