js 阻止弹出层底部页面滑动

注:代码可能和其他博客相似,毕竟原理都是一样的。

一、源码

<!DOCTYPE html>
<html >
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content=" />
    <title>弹出层底部不能滑动</title>
    <style>
      html,
      body {
        padding: 0;
        margin: 0;
      }
      .outer-box {
        height: 1700px;
        width: 100%;
        background-color: brown;
        overflow: auto;
      }
      /*btn按钮样式*/
      button {
        height: 60px;
      }
      /* 弹出层蒙版 */
      .div-pop {
        display: none;
        position: fixed;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1;
      }
      /*弹出层内容*/
      .pop-content {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        height: 50%;
        width: 50%;
        z-index: 20;
        background: beige;
      }
    </style>
  </head>
  <body>
    <div >
      <button onclick="pop()">打开弹窗</button>
      <!--弹出层-->
      <div >
        <!--弹出层内容-->
        <div >
          <button  onclick="closePop()">关闭弹出层</button>
        </div>
      </div>
    </div>
    <script>
      function pop() {
        //pc端
        document.getElementsByClassName('div-pop')[0].style.cssText = 'display:block';
        document.body.style.cssText = 'overflow:hidden;height:100%;';
        //移动端
        document.getElementsByClassName('div-pop')[0].addEventListener(
          'touchstart',
          function (e) {//移动端阻止默认行为和冒泡
            e.stopPropagation();
            e.preventDefault();
          },
          false
        );
      }
      //移动端
      document.getElementById('close').addEventListener(
        'touchstart',
        function () {
          document.getElementsByClassName('div-pop')[0].style.cssText = 'display:none';
        },
        false
      );
      //pc端
      function closePop() {
        document.getElementsByClassName('div-pop')[0].style.cssText = 'display:none';
        document.body.style.cssText = 'overflow:auto';
      }
    </script>
  </body>
</html>

二、效果

PC端
在这里插入图片描述
移动端(小米手机为例)在这里插入图片描述

三、原理

PC端:当点击弹出层时,调用如下代码

        document.getElementsByClassName('div-pop')[0].style.cssText = 'display:block';
        document.body.style.cssText = 'overflow:hidden;height:100%;';

其中最关键的是把body的样式设置为overflow:hidden;height:100%;,这样就并不会出现滚动条和滑动

移动端:滑动是通过手指接触屏幕滑动的,所以调用touchstart事情来禁止滑动。
其中禁止冒泡是因为z-index值高的会优先触发事件监听,从而控制不让事件流继续流到body中出现滑动(滚动条)

document.getElementsByClassName('div-pop')[0].addEventListener(
          'touchstart',
          function (e) {//移动端阻止默认行为和冒泡
            e.stopPropagation();
            e.preventDefault();
          },
          false
        );
        //移动端
      document.getElementById('close').addEventListener(
        'touchstart',
        function () {
          document.getElementsByClassName('div-pop')[0].style.cssText = 'display:none';
        },
        false
      );

如有错误欢迎指出