jQuery UI - 외부 클릭 시 대화상자 닫기
특정 요소를 클릭하면 표시되는 jQuery UI Dialog가 있습니다.해당 트리거 요소 또는 대화 상자 자체가 아닌 다른 곳에서 클릭이 발생하면 대화 상자를 닫습니다.
대화 상자를 여는 코드는 다음과 같습니다.
$(document).ready(function() {
var $field_hint = $('<div></div>')
.dialog({
autoOpen: false,
minHeight: 50,
resizable: false,
width: 375
});
$('.hint').click(function() {
var $hint = $(this);
$field_hint.html($hint.html());
$field_hint.dialog('option', 'position', [162, $hint.offset().top + 25]);
$field_hint.dialog('option', 'title', $hint.siblings('label').html());
$field_hint.dialog('open');
});
/*$(document).click(function() {
$field_hint.dialog('close');
});*/
});
마지막 부분에 대한 설명을 해제하면 대화 상자가 열리지 않습니다.대화상자가 열리는 것과 같은 클릭으로 다시 닫히기 때문인 것 같습니다.
최종 작업 코드
참고: jQuery outside events 플러그인을 사용합니다.
$(document).ready(function() {
// dialog element to .hint
var $field_hint = $('<div></div>')
.dialog({
autoOpen: false,
minHeight: 0,
resizable: false,
width: 376
})
.bind('clickoutside', function(e) {
$target = $(e.target);
if (!$target.filter('.hint').length
&& !$target.filter('.hintclickicon').length) {
$field_hint.dialog('close');
}
});
// attach dialog element to .hint elements
$('.hint').click(function() {
var $hint = $(this);
$field_hint.html('<div style="max-height: 300px;">' + $hint.html() + '</div>');
$field_hint.dialog('option', 'position', [$hint.offset().left - 384, $hint.offset().top + 24 - $(document).scrollTop()]);
$field_hint.dialog('option', 'title', $hint.siblings('label').html());
$field_hint.dialog('open');
});
// trigger .hint dialog with an anchor tag referencing the form element
$('.hintclickicon').click(function(e) {
e.preventDefault();
$($(this).get(0).hash + ' .hint').trigger('click');
});
});
너무 오래 끌어서 미안하지만 아래 내용을 사용했습니다.단점이 있습니까?열린 기능 보기...
$("#popup").dialog(
{
height: 670,
width: 680,
modal: true,
autoOpen: false,
close: function(event, ui) { $('#wrap').show(); },
open: function(event, ui)
{
$('.ui-widget-overlay').bind('click', function()
{
$("#popup").dialog('close');
});
}
});
다른 플러그인 사용을 잊어버림:
다음은 외부 팝업을 클릭할 때 jquery UI 대화상자를 닫는 세 가지 방법입니다.
대화 상자가 modal/background overlay인 경우: http://jsfiddle.net/jasonday/6FGqN/
jQuery(document).ready(function() {
jQuery("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 100,
modal: true,
open: function(){
jQuery('.ui-widget-overlay').bind('click',function(){
jQuery('#dialog').dialog('close');
})
}
});
});
대화상자가 modal 이외의 방법 1: 방법 1: http://jsfiddle.net/jasonday/xpkFf/
// Close Pop-in If the user clicks anywhere else on the page
jQuery('body')
.bind(
'click',
function(e){
if(
jQuery('#dialog').dialog('isOpen')
&& !jQuery(e.target).is('.ui-dialog, a')
&& !jQuery(e.target).closest('.ui-dialog').length
){
jQuery('#dialog').dialog('close');
}
}
);
Non-Modal 대화방식 2: http://jsfiddle.net/jasonday/eccKr/
$(function() {
$( "#dialog" ).dialog({
autoOpen: false,
minHeight: 100,
width: 342,
draggable: true,
resizable: false,
modal: false,
closeText: 'Close',
open: function() {
closedialog = 1;
$(document).bind('click', overlayclickclose);
},
focus: function() {
closedialog = 0;
},
close: function() {
$(document).unbind('click');
}
});
$('#linkID').click(function() {
$('#dialog').dialog('open');
closedialog = 0;
});
var closedialog;
function overlayclickclose() {
if (closedialog) {
$('#dialog').dialog('close');
}
//set to one because click on dialog box sets to zero
closedialog = 1;
}
});
jQuery Outside Events 플러그인을 확인합니다.
할 수 있습니다.
$field_hint.bind('clickoutside',function(){
$field_hint.dialog('close');
});
이 글로벌 스크립트를 추가하면 모든 모달 대화상자가 종료되고 아웃사이트를 클릭하기만 하면 됩니다.
$(document).ready(function()
{
$(document.body).on("click", ".ui-widget-overlay", function()
{
$.each($(".ui-dialog"), function()
{
var $dialog;
$dialog = $(this).children(".ui-dialog-content");
if($dialog.dialog("option", "modal"))
{
$dialog.dialog("close");
}
});
});;
});
$(".ui-widget-overlay").click (function () {
$("#dialog-id").dialog( "close" );
});
동작 중인 위의 코드를 표시하는 Fiddle.
저는 두 부분을 해야 했습니다.먼저 외부 클릭 핸들러:
$(document).on('click', function(e){
if ($(".ui-dialog").length) {
if (!$(e.target).parents().filter('.ui-dialog').length) {
$('.ui-dialog-content').dialog('close');
}
}
});
이 전화는dialog('close')
총칭으로ui-dialog-content
class, 클릭이 하나에서 시작되지 않은 경우 모든 대화 상자가 닫힙니다.오버레이가 구성 요소의 일부가 아니므로 modal(모달) 대화 상자에서도 작동합니다..ui-dialog
자
문제는 다음과 같습니다.
- 대부분의 대화상자는 대화상자 외부의 클릭으로 인해 작성됩니다.
- 이 핸들러는 클릭이 대화상자를 만들고 문서에 버블링된 후 실행되므로 즉시 닫힙니다.
이 문제를 해결하기 위해 다음과 같은 클릭 핸들러에 stopPropagation을 추가해야 했습니다.
moreLink.on('click', function (e) {
listBox.dialog();
e.stopPropagation(); //Don't trigger the outside click handler
});
이 질문은 좀 오래된 질문이지만, 사용자가 어딘가를 클릭할 때 모달이 아닌 대화상자를 닫고 싶을 때는 JQuery UI Multisellect 플러그인에서 가져온 것을 사용하면 됩니다.주요 장점은 클릭이 "잃어버린" 상태가 아니라는 것입니다(사용자가 링크나 버튼을 클릭하고 싶을 경우, 동작이 완료됩니다).
$myselector.dialog({
title: "Dialog that closes when user clicks outside",
modal:false,
close: function(){
$(document).off('mousedown.mydialog');
},
open: function(event, ui) {
var $dialog = $(this).dialog('widget');
$(document).on('mousedown.mydialog', function(e) {
// Close when user clicks elsewhere
if($dialog.dialog('isOpen') && !$.contains($myselector.dialog('widget')[0], e.target)){
$myselector.dialog('close');
}
});
}
});
추가 플러그인을 사용하지 않고도 이 작업을 수행할 수 있습니다.
var $dialog= $(document.createElement("div")).appendTo(document.body);
var dialogOverlay;
$dialog.dialog({
title: "Your title",
modal: true,
resizable: true,
draggable: false,
autoOpen: false,
width: "auto",
show: "fade",
hide: "fade",
open:function(){
$dialog.dialog('widget').animate({
width: "+=300",
left: "-=150"
});
//get the last overlay in the dom
$dialogOverlay = $(".ui-widget-overlay").last();
//remove any event handler bound to it.
$dialogOverlay.unbind();
$dialogOverlay.click(function(){
//close the dialog whenever the overlay is clicked.
$dialog.dialog("close");
});
}
});
여기 $dialog가 대화 상자입니다.기본적으로 우리가 하는 일은 이 대화상자가 열릴 때마다 마지막 오버레이 위젯을 가져오고, 오버레이가 클릭될 때마다 클릭 핸들러를 해당 오버레이에 바인딩하여 $dialog를 닫는 것입니다.
외부 이벤트 플러그인이 필요 없습니다...
.ui-widget-overlay div에 이벤트 핸들러를 추가하기만 하면 됩니다.
jQuery(document).on('click', 'body > .ui-widget-overlay', function(){
jQuery("#ui-dialog-selector-goes-here").dialog("close");
return false;
});
jQueryui 대화상자에 사용한 셀렉터도 호출되어 닫히는지 확인합니다.즉, #ui-selector-goes-dialog-여기
이것은 jQuery UI를 사용하는 것이 아니라 jQuery를 사용하며, jQuery UI를 사용하지 않는 사람들에게 어떤 이유로든 유용할 수 있습니다.이렇게 합니다.
function showDialog(){
$('#dialog').show();
$('*').on('click',function(e){
$('#zoomer').hide();
});
}
$(document).ready(function(){
showDialog();
});
그래서 대화상자를 보여주면 어떤 것이든 처음 클릭하는 것만 찾는 클릭 핸들러를 추가합니다.
이제 #dialog의 모든 클릭과 해당 내용을 무시하도록 할 수 있다면 더 좋겠지만 $('*')를 $('not(#dialog, #dialog *'))로 바꾸려고 해도 여전히 #dialog 클릭이 감지됩니다.
어쨌든 이건 순전히 포토 라이트 박스용으로 사용하고 있어서 그 용도로는 괜찮았습니다.
주어진 예제는 ID가 '#dialog'인 하나의 대화 상자를 사용합니다. 대화 상자를 닫는 솔루션이 필요했습니다.
$.extend($.ui.dialog.prototype.options, {
modal: true,
open: function(object) {
jQuery('.ui-widget-overlay').bind('click', function() {
var id = jQuery(object.target).attr('id');
jQuery('#'+id).dialog('close');
})
}
});
프로토타입 사용을 제안해 준 동료 유리 아르케스틴에게 감사드립니다.
이 방법이 NON-MODAL 대화 상자에 사용할 수 있는 유일한 방법입니다.
$(document).mousedown(function(e) {
var clicked = $(e.target); // get the element clicked
if (clicked.is('#dlg') || clicked.parents().is('#dlg') || clicked.is('.ui-dialog-titlebar')) {
return; // click happened within the dialog, do nothing here
} else { // click was outside the dialog, so close it
$('#dlg').dialog("close");
}
});
모든 크레딧은 액슬로 전송됩니다.
비모달 대화상자 외부를 클릭하여 닫습니다.
관심 있는 분들을 위해 modal 또는 non-modal 대화 상자 외부를 클릭할 때 대화 상자를 닫을 수 있는 일반 플러그인을 만들었습니다.동일한 페이지에서 하나 또는 여러 개의 대화 상자를 지원합니다.
자세한 내용은 여기: http://www.coheractio.com/blog/closing-jquery-ui-dialog-widget-when-clicking-outside
로랑
여기에 게시된 솔루션을 기반으로 사용합니다.
var g_divOpenDialog = null;
function _openDlg(l_d) {
// http://stackoverflow.com/questions/2554779/jquery-ui-close-dialog-when-clicked-outside
jQuery('body').bind(
'click',
function(e){
if(
g_divOpenDialog!=null
&& !jQuery(e.target).is('.ui-dialog, a')
&& !jQuery(e.target).closest('.ui-dialog').length
){
_closeDlg();
}
}
);
setTimeout(function() {
g_divOpenDialog = l_d;
g_divOpenDialog.dialog();
}, 500);
}
function _closeDlg() {
jQuery('body').unbind('click');
g_divOpenDialog.dialog('close');
g_divOpenDialog.dialog('destroy');
g_divOpenDialog = null;
}
한 페이지에 미리보기 모달을 만드는 과정에서 동일한 문제가 발생했습니다.구글 검색을 많이 한 후에 저는 이 매우 유용한 해결책을 발견했습니다.이벤트 및 대상을 사용하면 클릭이 발생한 위치를 확인하고 그에 따라 작업을 트리거하거나 아무것도 수행하지 않습니다.
$('#modal-background').mousedown(function(e) {
var clicked = $(e.target);
if (clicked.is('#modal-content') || clicked.parents().is('#modal-content'))
return;
} else {
$('#modal-background').hide();
}
});
̇트는 플러그인이 필요 없고 jquery나 간단한 자바스크립트로 할 수 있습니다.
$('#dialog').on('click', function(e){
e.stopPropagation();
});
$(document.body).on('click', function(e){
master.hide();
});
전체 DOM에서 $('.any-selector')를 사용하여 대화 내용을 찾는 것이 그렇게 밝다고 생각하지 않습니다.
해라
$('<div />').dialog({
open: function(event, ui){
var ins = $(this).dialog('instance');
var overlay = ins.overlay;
overlay.off('click').on('click', {$dialog: $(this)}, function(event){
event.data.$dialog.dialog('close');
});
}
});
대화 상자 인스턴스에 포함된 오버레이를 실제로 사용하는 것입니다. 이렇게 하면 일이 절대로 잘못되지 않습니다.
다음 코드를 사용하여 대화상자의 '닫기' 버튼 클릭을 시뮬레이션 할 수 있습니다(자신의 대화상자 이름에 대해 'MY_DIALOG' 문자열 변경).
$("div[aria-labelledby='ui-dialog-title-MY_DIALOG'] div.ui-helper-clearfix a.ui-dialog-titlebar-close")[0].click();
스마트 코드: 모든 것이 명확하고 가독성을 유지하기 위해 다음 코드를 사용하고 있습니다.외부 본체가 대화 상자를 닫습니다.
$(document).ready(function () {
$('body').on('click', '.ui-widget-overlay', closeDialogBox);
});
function closeDialogBox() {
$('#dialog-message').dialog('close');
}
페이지의 열려 있는 대화 상자에서 작동해야 하는 이 코드를 사용하게 되었고, 도구 설명 클릭을 무시하고 대화 상자가 닫히는 리소스도 정리했습니다.
$(document).mousedown(function(e) {
var clicked = $(e.target); // get the element clicked
if (clicked.is('.ui-dialog-content, .ui-dialog-titlebar, .ui-tooltip') || clicked.parents().is('.ui-dialog-content, .ui-dialog-titlebar, .ui-tooltip')) {
return; // click happened within the dialog, do nothing here
} else { // click was outside the dialog, so close it
$('.ui-dialog-content').dialog("close");
$('.ui-dialog-content').dialog("destroy");
$('.ui-dialog-content').detach();
}
});
요소를 제외한 클릭으로 .dialog(s)를 닫아야 하는 필요성을 발견했습니다.저는 정보 대화가 많은 페이지가 있어서, 그것들을 모두 처리할 수 있는 무언가가 필요했습니다.내가 처리한 방법은 이렇습니다.
$(document).ready(function () {
$(window).click(function (e) {
$(".dialogGroup").each(function () {
$(this).dialog('close');
})
});
$("#lostEffClick").click(function () {
event.stopPropagation();
$("#lostEffDialog").dialog("open");
};
});
언급URL : https://stackoverflow.com/questions/2554779/jquery-ui-close-dialog-when-clicked-outside
'programing' 카테고리의 다른 글
최근 한 시간 동안 수정된 테이블 찾기 쿼리 (0) | 2023.10.29 |
---|---|
안드로이드:사용자 이름과 암호를 저장하고 있습니까? (0) | 2023.10.29 |
$httpProvider.response의 대안요격기 (0) | 2023.10.29 |
Angular JS를 사용하여 양식의 여러 제출 버튼을 처리하는 방법? (0) | 2023.10.29 |
Wordpress에서 사용자 지정 게시물 유형에 대한 사용자 지정 이미지 크기 (0) | 2023.10.29 |