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

此生再无相见时 提交于 2020-01-17 03:36:22

问题


I'm trying to hide a div both when 1) certain other divs are clicked, and when 2) empty space on the margins of the page are clicked, space not contained by any div. I've got the first part covered, but I do not know how to do the second. I don't want the div to hide when ANYTHING outside the div is clicked. Just when empty space is clicked.

Here's a simple jsfiddle to play with.

And here's the basic jsquery I'm using. Can I add something that will make "text1" or "text2" disappear when the user clicks empty space?

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

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

回答1:


You can simply add a specific class to the div items that will be clicked and do this:

$(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      
    }      
});

DEMO: https://jsfiddle.net/tjrsvbuc/3/




回答2:


I found this beaufitul solution here on Stackoverflow:

$(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




回答3:


Hope this is you looking for add an event in 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);
  });


来源:https://stackoverflow.com/questions/30190625/trigger-event-in-jsquery-when-clicking-on-empty-space-outside-of-any-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!