[英]Can't figure out how to close modal by clicking outside window
無論我嘗試什么,它都不適合我。 我希望用戶點擊一個蘋果並顯示一個模式。 我在模態框內放置了一個“x”來關閉它。 我只需要知道如何通過單擊模式外部來關閉它。
這是蘋果按鈕的 JavaScript 代碼:
<script>
var ambModal = $('#ambPopup');
$('#amb').click(function() {
ambModal.show();
});
$('.ambClose').click(function() {
ambModal.hide();
});
</script>
這非常有效,但我已經在互聯網上搜索了解決方案,但我嘗試過的任何方法都沒有解決我的問題。 我確實在 HTML 中加載了 jQuery。 這個 function 是否需要引導程序才能工作? 有可能我的 header 弄錯了。
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Apples2Apples</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="applestyles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap" rel="stylesheet">
<!--FONT FOR BODY-->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Raleway&display=swap" rel="stylesheet">
我錯過了什么嗎? 請有人回復,如果可以的話。 謝謝!
不確定您的用例,但對我有用的是在模態后面包含一個額外的元素(如覆蓋,但如果您願意,可以是透明的)以捕捉模態 window 之外的點擊。 這是一個例子。
$("body").on("click", '.toggle-modal', function() { if ($('#ambPopup').is(":visible")) { $('#ambPopup').fadeOut("fast", function() { $(this).remove(); }); } else { const modal = $("<div />", { "id": "ambPopup" }).append( $("<div />", { "class": "modal-overlay toggle-modal" }), $("<div />", { "class": "modal-content" }).text("Content for the modal. Can be dynamic too.").append( $("<div />", { "class": "modal-close toggle-modal" }) ) ).appendTo("body").fadeIn("fast").css("display", "flex"); } });
body, html { margin: 0; padding: 0; width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; } #ambPopup { display: none; position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 9000; }.modal-overlay { position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 1; background: rgba(0, 0, 0, .1); cursor: pointer; }.modal-content { background: white; padding: 30px; font-size: 16px; line-height: normal; text-align: center; z-index: 2; position: relative; margin: auto; }.modal-close { position: absolute; top: 0; right: 10px; width: 20px; height: 20px; border-radius: 50%; background: red; transform: translate(0, -50%); cursor: pointer; z-index: 10; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="toggle-modal">Show modal</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.