Prevent background scrolling when overlay appears

无人久伴 提交于 2019-12-05 19:59:22

One approach is hidden the overflow of the body element.

like this:

body.modal-open{
    overflow:hidden;
}

so in this case when you popup the modal you add a class to body and then when you close it you remove that class.

another approach is using a javascript to disable the scroll like this:

   document.documentElement.style.overflow = 'hidden';
   document.body.scroll = "no";

and then return it with

 document.documentElement.style.overflow = 'scroll';
 document.body.scroll = "yes";

When you open the modal, you can add overflow: hidden; to the body's style.

Or,

body.modal-opened {
   overflow: hidden;
}

And add modal-opened class to the body when opening and remove when you close the dialog.

When the modal opens, hide the x/y scroll bars on the body.

.no-scroll {
    overflow: hidden;
}

Using JavaScript add the class to the body:

<body class="no-scroll">

</body>

Once you close the modal remove the class.

Using JavaScript to add a class to the body with

overflow:hidden;

will work in most cases, but I beleive Safari on iPhone will still scroll slightly with jitter due to Touch Move and something like this will be needed.

function handleTouchMove(e)
{
  e.preventDefault();
}
function lockscreen()
{
  var body = document.getElementById("body");
  body.className += " lock-screen";
  body.addEventListener('touchmove', handleTouchMove, false);
}
function unlock()
{
  var body = document.getElementById("body");
 body.classList.remove("lock-screen");
 body.removeEventListener('touchmove', handleTouchMove);
}

to stop the user from still scrolling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!