Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

jquery - Hide a div when clicked outside of it

This question has been asked multiple times, however none of the answers seem to work for me.

The css of the div is as follows:

#info{
  display: none;
  position: fixed;
  z-index: 500;
  height: 50%;
  width: 60%;
  overflow: auto;
  background: rgba(187, 187, 187, .8);
}

I tried to use the following code:

$("#info").click(function(e){
  e.stopPropagation();
});

$(document).click(function(){
  $("#info").hide();
});

as well as this code:

$(document).mouseup(function (e){
    var container = $("#info");

    if (container.has(e.target).length === 0) {
        container.hide();
    }
});

Yet whenever i click on the div it also disappears, no clue why but it does.
Any thing else that might work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As your target has id=info, so you can try:

$(document).click(function(e) {

  // check that your clicked
  // element has no id=info

  if( e.target.id != 'info') {
    $("#info").hide();
  }
});

You can also try:

$(document).click(function() {

  if( this.id != 'info') {
    $("#info").hide();
  }

});

According to comment

$(document).click(function(e) {

    // check that your clicked
    // element has no id=info
    // and is not child of info
    if (e.target.id != 'info' && !$('#info').find(e.target).length) {
        $("#info").hide();
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...