需求分析

  • 弹窗实现: 通过蒙层mask + 窗口区域实现
  • 弹窗通过一个容器元素container包裹蒙层mask元素和窗口元素
  • 滚动是在body区域滚动的

    实现方式

  • 通过 preventDefault 方法去禁止滚动

    1. // 禁止滚动
    2. document.body.addEventListener("touchmove", function(e) {
    3. e.preventDefault():
    4. });
    5. // 允许滚动
    6. document.body.addEventListener("touchmove", function(e) {
    7. e.returnValue = true:
    8. });

    将以上代码添加在打开弹窗的代码上会造成关闭弹窗后,窗口依旧无法滚动(ios测试, Android未测试)

  • 事件默认处理方式是冒泡模式, touchmove 事件是在弹窗上操作的, 禁止事件冒泡,事件是不是就不会触发 body 滚动了

    1. const [container] = document.getElementByTagName("container");
    2. container.addEventListener("touchmove", function(e) {
    3. e.stopPropagation();
    4. });

    将以上代码添加到弹窗元素渲染到页面上后,执行的js中未测试不确定能行不能行

  • 最后代码,强制事件处理为冒泡模式(不清楚是不是所有的浏览器默认是冒泡)

    1. const [container] = document.getElementByTagName("container");
    2. container.addEventListener("touchmove", function(e) {
    3. e.stopPropagation();
    4. // 阻止默认行为 --- 有可能弹窗自己能滚动
    5. e.preventDefault():
    6. }, false);