简体   繁体   English

防止滚动模式框内容时滚动背景div

[英]Prevent scrolling of the background div on scrolling the modal box content

I have a modalbox for for mobile site(ios device), which contains scrollable content inside it. 我有一个用于移动网站(iOS设备)的模式框,其中包含可滚动的内容。 The initial issue was that on scrolling the content inside the modal, even the background page was scrollable. 最初的问题是在滚动模式内部的内容时,即使背景页面也是可滚动的。 To fix this, I added a 'position: fixed' property to the body tag when the modalbox is opened, and removing it when the modalbox is closed. 为了解决这个问题,我在打开模态框时向body标签添加了“position:fixed”属性,并在关闭模态框时将其删除。

Though this fixes the initial scroll issue, it causes the page to scroll to top on adding the "fixed property:" to the body tag and and the page scrolls to the initial position once the modalbox is closed. 虽然这解决了初始滚动问题,但它会导致页面在向body标签添加“fixed property:”时滚动到顶部,并且一旦模态框关闭,页面就会滚动到初始位置。

Wanted a solution to avoid the page being scrolled to top if fixed property is added to the body. 想要一个解决方案,以防止在将固定属性添加到正文时将页面滚动到顶部。

One way to do this would be monitor touch and wheel events and call preventDefault on them when you know they are going to scroll wrong element. 实现此目的的一种方法是监视触摸和滚轮事件,并在知道它们将要滚动错误的元素时调用preventDefault。 Here's main idea: 这是主要的想法:

element.addEventListener('touchstart', onTouchStart);
element.addEventListener('touchmove', onTouchMove, { passive: false });
element.addEventListener('wheel', onWheel, { passive: false });

onWheel(event) {
  // Walk up the DOM tree from target element until the 
  // topmost element you want to isolate scroll with
  // i.e. your modal and check if any of the elements
  // can be scrolled in the wheel direction (event.deltaY).
  // If there are no such elements, call event.preventDefault().
}

onTouchStart(event) {
  // Store initial touch coordinates to determine direction later
}

onTouchMove(event) {
  // Using initial touch coordinates determine direction of the move
  // and do the similar thing as with the wheel event — call
  // event.preventDefault() if you know that resulting scroll will happen
  // outside of your modal
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM