单击任何 div 之外的空 space 时在 jquery 中触发事件

Trigger event in jsquery when clicking on empty space, outside of any div

我试图在以下情况下隐藏 div:1) 单击某些其他 div,以及 2) 单击页面边缘的空白 space , space 未包含在任何 div 中。我已经涵盖了第一部分,但我不知道如何做第二部分。我不希望 div 在单击 div 之外的任何内容时隐藏。就在点击空 space 的时候。

这里有一个简单的 jsfiddle 可以玩。

这是我正在使用的基本 jsquery。我可以添加一些东西,使 "text1" 或 "text2" 在用户单击空 space 时消失吗?

$("#2").click(function() {
   $('#text1').slideUp(300);
});

$("#1").click(function() {
   $('#text2').slideUp(300);
});

我找到了这个完美的解决方案 here on Whosebug:

$(document).mouseup(function (e)
{
    var container = $("#text1, #text2");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.slideUp(300);
    }
});

Updated Fiddle

希望这是您要在 javascript e.stopPropagation();

中添加活动
$(document).ready(function(){
                $("#1").click(function(e){
                    e.stopPropagation(); 
                    $("#text1").slideDown(300);
                });
            });

$(document).ready(function(e){
                $("#2").click(function(e){
                    e.stopPropagation(); 
                    $("#text2").slideDown(300);
                });
            });

$("#2").click(function() {
                $('#text1').slideUp(300);
            });

$("#1").click(function() {
                $('#text2').slideUp(300);
            });

$("body").click(function() {
    $('#text1').slideUp(300);
    $('#text2').slideUp(300);
  });

您只需将特定的 class 添加到将被点击的 div 项目,然后执行此操作:

$(document).click(function (event) {//when anywhere is clicked on the page    
    if (!$(event.target).hasClass('MyClass')) {//if the clicked item has this class
        $('#text2').slideUp(300);//hide     
        $('#text1').slideUp(300);//hide      
    }      
});

演示:https://jsfiddle.net/tjrsvbuc/3/