在iOS上的模态JS外部单击时关闭模态 [英] Close modal on click outside of the modal JS on iOS
问题描述
当用户在 iOS 和非触摸设备上在模式窗口之外单击时,如何将代码close
设置为modal
?
How do I make this code close
a modal
when user clicks outside of the modal window both on iOS and non-touch devices?
我在这里了解有关window.onclick
和touch
设备的其他一些类似主题,但是对于JS来说我还比较陌生,我不知道如何正确组合此功能(对于两个平台).
I know about some other similar topics here regarding window.onclick
and touch
devices, but I'm relatively new to JS and I don't know how to properly combine this function (for both platforms).
var modal = document.getElementById('myModal');
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
var closeModal = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
window.addEventListener('click', closeModal);
window.addEventListener('touchend', closeModal);
.modal {
display: none;
position: fixed;
overflow: hidden;
left: 0;
bottom: 0;
width: 100%;
height: auto;
background-color: black;
color: white;
font-size: 100%;
}
.close {
color: white;
float: right;
font-size: 70%;
}
.close:hover, .close:focus {
color: #000;
text-decoration: none;
}
<div id="myModal" class="modal">
<span class="close">×</span>
<p>Some content here</p>
</div>
推荐答案
将touchend
和click
事件绑定到窗口元素:
Bind touchend
and click
event to the window element:
var modal = document.getElementById('myModal');
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
var state = 'closed';
btn.onclick = function() {
modal.style.display = "block";
setTimeout(function() {
state = 'open';
}, 300);
}
span.onclick = function() {
modal.style.display = "none";
}
var closeModal = function(event) {
var closest = event.target.closest('#myModal');
if ((null === closest || 0 < closest.length) && 'open' === state) {
modal.style.display = "none";
state = 'closed';
}
}
window.addEventListener('click', closeModal);
window.addEventListener('touchend', closeModal);
.modal {
display: none;
position: fixed;
overflow: hidden;
left: 0;
bottom: 0;
width: 100%;
height: auto;
background-color: black;
color: white;
font-size: 100%;
}
.close {
color: white;
float: right;
font-size: 70%;
}
.close:hover, .close:focus {
color: #000;
text-decoration: none;
}
<button id="myBtn">open</button>
<div id="myModal" class="modal">
<span class="close">×</span>
<p>Some content here</p>
</div>
:更新了代码段.
在该解决方案上,我添加了一个简单的状态以仅在状态为open
时运行关闭方法.使用最接近方法,我们搜索了单击的元素(如果存在等于modal
的元素).
On that solution i added simple a state to run close method only when state is open
. With the closest method we search over all parent of the clicked element if there is a element that is equal to modal
.
仅当closest
为空或长度为0时,我们才会关闭模态.
Only when closest
is null or has a length of 0 we will close the modal.
这篇关于在iOS上的模态JS外部单击时关闭模态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!