Found稍作修改的W3学校代码,用于关闭模态窗口外部的单击时关闭模态,在iOS上运行良好(W3的代码在iOS上不起作用),但是当我尝试对其进行更改以添加时一些功能,例如:
当用户单击按钮-模态打开(工作)时,当用户在模态窗口之外单击-模态关闭(工作)时,当用户在模态仍然打开时再次单击按钮-模态关闭(不工作)。无法弄清楚如何使其工作,请帮助
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>
这是我发现的原始代码,我已经尝试了所有可能的变体,并且我认为问题出在eventListener中,但主要的问题是如何使这三个简单任务正常工作(尤其是在触摸设备,iOS上) )
btn.onclick = function() {
if (modal.style.display == "none") {
modal.style.display = "block";
setTimeout(function() {state = 'open';}, 300);
} else {
modal.style.display = "none";
state = 'close';
}