簡體   English   中英

模態不會在手機上關閉

[英]modal won't close on mobile

我正在使用JS模態(沒有jquery),因為這種方法存在一些問題...

一切正常,除了移動用戶無法關閉它。

var modal = document.getElementById('myModal');
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
};

我可能缺少這種觸感...

我試過這樣的jQuery:

$(document).ready(function(){
    $(modal).on('click touchstart', function() {
        modal.style.display = "none";
    });
});

這里的問題是,如果用戶在模式中單擊,它也會消失。

我需要的是,當用戶僅在外部單擊時,模態應該消失...

有什么想法可以解決這個問題嗎?

謝謝。

而不是注冊單擊目標,請注冊文檔,然后檢查鼠標不在目標內

$(document).on ('mouseup touchstart', function (e)
{
    var container = $("#myModal");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});

您是否嘗試過使用contains

我剛剛在iOS Safari和Chrome上進行了測試,它可以正常工作

請查看演示,

當您單擊黃色部分時,它仍然存在

但是,當您單擊粉紅色部分時,整個模態將隱藏

JS斌

JS Bin中的代碼

var pa = document.querySelector('#modal-overlay');
var ch = document.querySelector('#modal-container');

pa.addEventListener('click', function(e) {
  if (!ch.contains(e.target)) {
    pa.style.display = 'none';
  }
});

您可以偵聽文檔上的“ mousedown”事件,然后檢查模式是否在事件路徑中。 如果不是,則隱藏模態。 如果是,則什么也不做。

 var myModal = document.getElementById('myModal'); document.addEventListener('mousedown', function(e) { if (e.path.indexOf(myModal) == -1) myModal.hidden = true; }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM