jquery: get mouse click if inside a div or not

后端 未结 6 1122
栀梦
栀梦 2020-12-29 08:46

i have this HTML page



a
b
c
d
相关标签:
6条回答
  • 2020-12-29 08:49

    If you want to detect whether or not you've clicked inside or outside the div, set the event handler on the documentElement and let it propagate from the other elements upwards:

    $("html").click(function (e)
    {
        if (e.target == document.getElementById("in_or_out"))
            alert("In");
        else
            alert("Out!");
    });
    
    0 讨论(0)
  • 2020-12-29 08:57

    for inside it would be

    $("#in_or_out").click(function() {
        // do something here
    });
    

    for outside...I've got no idea.

    Edit: You could try to do the same for body-tag (assigning a click-handler to the document itself). But I'm not sure if both events would fire by that.

    0 讨论(0)
  • 2020-12-29 09:01

    Depends what you want. If you only want to execute code, when it was inside #in_or_out, you can do:

    $('#in_or_out').click(function(){ /* your code here */ });
    

    You can have a status variable that says whether the mouse is in #in_or_out or not:

    var inside = false;
    
    $('#in_or_out').hover(function() { inside = true; }, function() { inside = false; });
    

    Then whenever a click occurs you can check with inside whether the click was inside in_or_out or not.

    Reference: .hover()

    Update:

    No matter to which element you bind the click handler, you can always do this:

    $('element').click(function() {
         if ($(this).attr('id') !== 'in_or_not') {
    
         }
     });
    
    0 讨论(0)
  • 2020-12-29 09:02

    Maybe this one will help you

    $('body').click(function(){
        //do smth
    });
    $('div#in_or_out').click(function(e){
        e.stopPropagation();
        // do smth else
    });
    
    0 讨论(0)
  • 2020-12-29 09:08

    Like this?

    $("#in_or_out").click(function() {
        alert("IN DIV!");
    });
    
    0 讨论(0)
  • 2020-12-29 09:12
    $("body > div").click(function() {
        if ($(this).attr("id") == "in_or_out") {
            // inside
        } else {
            // not inside
        }
    });
    

    EDIT: just learned, that there is a negate:

    $("body > div:not(#in_or_out)").click(function(e) {
        // not inside
    });
    
    0 讨论(0)
提交回复
热议问题