需求分析
- 弹窗实现: 通过蒙层mask + 窗口区域实现
- 弹窗通过一个容器元素container包裹蒙层mask元素和窗口元素
-
实现方式
通过 preventDefault 方法去禁止滚动
// 禁止滚动
document.body.addEventListener("touchmove", function(e) {
e.preventDefault():
});
// 允许滚动
document.body.addEventListener("touchmove", function(e) {
e.returnValue = true:
});
将以上代码添加在打开弹窗的代码上会造成关闭弹窗后,窗口依旧无法滚动(ios测试, Android未测试)
事件默认处理方式是冒泡模式, touchmove 事件是在弹窗上操作的, 禁止事件冒泡,事件是不是就不会触发 body 滚动了
const [container] = document.getElementByTagName("container");
container.addEventListener("touchmove", function(e) {
e.stopPropagation();
});
将以上代码添加到弹窗元素渲染到页面上后,执行的js中未测试不确定能行不能行
最后代码,强制事件处理为冒泡模式(不清楚是不是所有的浏览器默认是冒泡)
const [container] = document.getElementByTagName("container");
container.addEventListener("touchmove", function(e) {
e.stopPropagation();
// 阻止默认行为 --- 有可能弹窗自己能滚动
e.preventDefault():
}, false);