2016-08-01 55 views
0

我使用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"; 
    }); 
}); 

這裏的問題是,如果裏面的用戶點擊它也將消失...

我需要的是當用戶只在外面點擊時,模態應該消失...

任何想法我該如何解決這個問題?

謝謝。

+0

您是否在尋找一個jQuery的解決方案?或者你願意堅持純粹的JS? – DBS

+0

我只是需要它的工作:-) – Morpheus

回答

0

,而不是目標點擊註冊,註冊的文檔,然後檢查,看看鼠標是不是目標

$(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(); 
    } 
}); 
+0

它不工作...它仍然沒有關閉... – Morpheus

+0

也嘗試綁定'touchstart',看我的編輯 – stackoverfloweth

+0

仍然一樣... – Morpheus

0

您是否嘗試過使用contains裏面?

我只是測試它在iOS Safari和Chrome,它工作正常

請查看演示,

當你點擊黃色部分,它仍然存在

然而

,當你點擊粉部分,整個模式將隱藏

JS Bin

代碼JS斌

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'; 
    } 
}); 
0

您可以在文檔上偵聽「mousedown」事件,然後檢查模態是否在事件路徑中。如果不是,則隱藏模式。如果是,那就什麼也不做。

var myModal = document.getElementById('myModal'); 
 

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

+0

我在這裏得到這個時,我運行此:「TypeError:e.path是未定義的」 – Morpheus

+0

好吧 - 進一步挖掘它看起來像event.path只支持在Chrome中。我在移動版Chrome瀏覽器上測試了這一功能,但它工作正常,但我不確定移動Safari的支持。其他人已經討論過這個問題,例如https://github.com/tmpvar/jsdom/issues/1563在那裏還有一個很好的解決方法,你可能想嘗試一下。 –