在我的网站上,我使用 JavaScript 打开一个模态/对话框,但是当用户单击同一 View 上的另一个选项卡时,模态仍然存在并妨碍。因此,如果用户单击模式,我想关闭它。但我不知道该怎么做,我知道 OnBlur 属性,但我还没有想出一个可行的解决方案。 这是我的脚本:
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 220,
width: 305,
modal: true,
buttons: {
'Spara': function () {
if (!validateNumber()) {
alert('Procent måste vara mellan 0-100');
return false;
}
if (!validateProject()) {
alert('Du måste välja ett project');
return false;
}
if (!validateDate()) {
return false;
}
locstring = "@(Url.Action("Index"))/Update/?";
locstring += '&projectId=' + $('#projectList').val();
locstring += '&startDate=' + $('#startDate').val();
locstring += '&endDate=' + $('#endDate').val();
locstring += '&pct=' + $('#pct').val();
var sid = $('#sId').text();
if (sid !== "") {
locstring += '&id=' + sid;
}
$.ajax({
type: "GET",
url: locstring,
dataType: "html",
success: function (data) {
$('#dialog').dialog('close');
reloadTable();
}
});
},
'Avbryt': function () {
$(this).dialog('close');
},
'Ta bort': function () {
var sid = $('#sId').text();
if (sid != "") {
locstring = "@(Url.Action("Index"))/Delete/" + sid;
$.ajax({
type: "GET",
url: locstring,
dataType: "html",
success: function(data) {
$('#dialog').dialog('close');
reloadTable();
}
});
}
}
},
close: function() {
allFields.val('').removeClass('ui-state-error');
}
});
$('#create-user').click(function() {
$('#dialog').dialog('open');
})
.hover(
function() {
$(this).addClass("ui-state-hover");
},
function() {
$(this).removeClass("ui-state-hover");
}
).mousedown(function() {
$(this).addClass("ui-state-active");
})
.mouseup(function() {
$(this).removeClass("ui-state-active");
});
});
最佳答案
有一个名为 isShowing
的标志,当对话框显示时,该标志设置为 true
,并将事件监听器附加到正文或主容器以检查单击。然后检查标志 isShowing
是否为 true,如果为 true
则隐藏对话框。
编辑 1
另一个解决方案,
HTML
<div id="dialog">Some demo text here.</div>
<div>some other demo text</div>
CSS
#dialog {
height: 300px;
width: 300px;
border: 2px solid orange;
}
JavaScript
document.addEventListener("click", function (e) {
if (e.target.id != "dialog") {
document.getElementById("dialog").style.display = "none";
}
});
这里我们比较点击元素的 ID,如果它不等于 dialog,那么我们隐藏对话框。
示例
关于如果用户点击其他地方,Javascript 关闭对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33146266/