移动端滚动穿透

2020-11-23  本文已影响0人  折叠幸福

这个问题解决N遍了,再此记录下,免得再遇到浪费脑细胞

情况一:弹窗里面没有滚动条

思路:阻止touchmove事件

modal.addEventListener('touchmove', function(e) {
e.preventDefault();
}, false);

VUE中语法糖@touchmove.prevent

情况二:弹窗里有滚动条

思路:打开弹窗,禁止body滚动;关闭弹窗 允许;难点是还原滚动条原来位置
弹窗开关:body增加/删除对应class,scrollTop 保存或者还原

先声明一个class,位置最好放在body同文件

.modal-open {
        position: fixed;
        width: 100%;
    }

打开弹窗后要执行的回调函数:

      this.middle_value = document.scrollingElement.scrollTop;  //保存滚动条位置
      document.body.classList.add('modal-open');
      document.body.style.top = -this.middle_value + 'px';

关闭弹窗回调函数:

     document.body.classList.remove('modal-open');
      document.scrollingElement.scrollTop = this.middle_value;
上一篇 下一篇

猜你喜欢

热点阅读