Close dialog on click (anywhere)

2019-01-08 08:06发布

Is there a default option to close a jQuery dialog by clicking somewhere on the screen instead of the close icon?

10条回答
贼婆χ
2楼-- · 2019-01-08 08:42

A bit late but this is a solution that worked for me. Perfect if your modal is inside the overlay tag. So, the modal will close when you click anywhere outside the modal content.

HTML

<div class="modal">  
  <div class="overlay">
    <div class="modal-content">
      <p>HELLO WORLD!</p>
    </div>
  </div>
</div>

JS

$(document).on("click", function(event) {
  if ($(event.target).has(".modal-content").length) {
    $(".modal").hide();
  }
});

Here is a working example

查看更多
可以哭但决不认输i
3楼-- · 2019-01-08 08:43

If the code of the previous posts doesn't work, give this a try:

$("a.ui-dialog-titlebar-close")[0].click();
查看更多
Deceive 欺骗
4楼-- · 2019-01-08 08:45

If you have several dialogs that could be opened on a page, this will allow any of them to be closed by clicking on the background:

$('body').on('click','.ui-widget-overlay', function() {
    $('.ui-dialog').filter(function () {
    return $(this).css("display") === "block";
    }).find('.ui-dialog-content').dialog('close');
});

(Only works for modal dialogs, as it relies on '.ui-widget-overlay'. And it does close all open dialogs any time the background of one of them is clicked.)

查看更多
ら.Afraid
5楼-- · 2019-01-08 08:45

If you'd like to do it for all dialogs throughout the site try the following code...

$.extend( $.ui.dialog.prototype.options, { 
    open: function() {
        var dialog = this;
        $('.ui-widget-overlay').bind('click', function() {
            $(dialog).dialog('close');
        });
    }   

});
查看更多
登录 后发表回答