繁体   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