簡體   English   中英

觸摸事件不適用於多個模態框

[英]Touch events not working on multiple Modal boxes

我試圖讓觸摸事件在多個模態框上運行,這樣當你點擊一個按鈕打開手機上的模態框時,你在模態框內向左/向右滑動,你應該得到一個警告框告訴你你用哪種方式滑動。

我試過用

document.getElementsByClassName("modalSwipe");

代替

document.getElementById("modalSwipe");

這當然是定位多個元素的正確方法,但隨后該功能將停止協同工作,並且不會出現任何警報。

我已經用Codepen上的整個代碼重新創建了我的問題,但這里是我懷疑是麻煩制造者的 js 腳本片段和部分 html。

我已經被這個問題困了兩天了,我開始質疑我的智商。 有沒有我在這里沒有看到的明顯解決方案?

非常感謝!

 // i suspect that a part of the problem starts within the function "init()" var lbl; function init() { lbl = document.getElementById("modalSwipe"); lbl.addEventListener("touchstart", startTouch, false); lbl.addEventListener("touchend", endTouch, false); lbl.addEventListener("touchmove", moveTouch, false); } var initialX = null; var initialY = null; function startTouch(e) { initialX = e.touches[0].clientX; initialY = e.touches[0].clientY; } function endTouch() { initialX = null; initialY = null; } function moveTouch(e) { if (initialX === null) { return; } if (initialY === null) { return; } var currentX = e.touches[0].clientX; var currentY = e.touches[0].clientY; var diffX = initialX - currentX; var diffY = initialY - currentY; if (Math.abs(diffX) > Math.abs(diffY)) { // sliding horizontally if (diffX > 0) { alert("Left"); // swiped left } else { alert("Right"); // swiped right } } else { return; } e.preventDefault(); }
 <section> <button class='button modalButton'>Modal 1</button> <!--and the other part of the problem lies here with modalSwipe --> <div class='modal modalid' id="modalSwipe"> <div class='modal-content'> <!-- no content for simplicity --> <div class='modal-header'> <span class='close'>X</span> <h2>Modal 1</h2> </div> </div> </div> </section>

查看您的 Codepen,我注意到您對模態使用了相同的 ID ( modalSwipe )。

ID 不應在多個元素上重復使用。

相反,您應該嘗試使用類名並找到活動模式。 你可以通過添加一個額外的類做active到活動模式。 關閉模態后,應刪除active類。

暫無
暫無

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

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