在iOS上的模态JS外部单击时关闭模态

时间:2018-09-26 10:36:18

标签: javascript ios modal-dialog

当用户在 iOS 和非触摸设备上均在模式窗口之外单击时,如何将代码close设为modal

我在这里了解有关window.onclicktouch设备的其他一些类似主题,但是对于JS来说我还比较陌生,我不知道如何正确组合此功能(对于两个平台)

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">&times;</span>

<p>Some content here</p>

</div>

1 个答案:

答案 0 :(得分:1)

touchendclick事件绑定到窗口元素:

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">&times;</span>

<p>Some content here</p>

</div>

编辑::更新了代码段。

在该解决方案上,我添加了一个简单的状态以仅在状态为open时运行关闭方法。使用closest方法,如果存在等于modal的元素,我们将搜索被单击元素的所有父元素。

仅当closest为null或长度为0时,我们才会关闭模式。