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

Javascript 在滚动模式框内容时防止滚动背景div,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有一个用于mobile siteios设备的modalbox,其中包含可滚动的内容。最初的问题是,在模式中滚动内容时,即使是背景页面也可以滚动。为了解决这个问题,我在打开modalbox时向body标记添加了一个“position:fixed”属性,并在关闭modalbox时将其删除 虽然这修复了初始滚动问题,但在添加固定属性时,会导致页面滚动到顶部:添加到body标记,并且一旦关闭modalbox,页面就会滚动到初始位置 想要一个解决方案,以避免在正文中添加固定属性时页面被滚动到顶部。一种方

我有一个用于mobile siteios设备的modalbox,其中包含可滚动的内容。最初的问题是,在模式中滚动内容时,即使是背景页面也可以滚动。为了解决这个问题,我在打开modalbox时向body标记添加了一个“position:fixed”属性,并在关闭modalbox时将其删除

虽然这修复了初始滚动问题,但在添加固定属性时,会导致页面滚动到顶部:添加到body标记,并且一旦关闭modalbox,页面就会滚动到初始位置


想要一个解决方案,以避免在正文中添加固定属性时页面被滚动到顶部。

一种方法是监视触摸和滚轮事件,并在知道它们将滚动错误元素时调用preventDefault。以下是主要观点:

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
}

你能分享你的代码吗?找到了一个运行良好的插件。只需在此处添加链接,以防任何人面临相同的问题: