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

时间:2019-03-19 09:29:39

标签: javascript jquery html css

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

尽管这可以解决初始滚动问题,但在将“ fixed property:”添加到body标签后,页面会滚动到顶部,并且一旦关闭了模式框,页面就会滚动到初始位置。

想要一种解决方案,以避免在将固定属性添加到正文的情况下将页面滚动到顶部。

1 个答案:

答案 0 :(得分:0)

执行此操作的一种方法是监视触摸和滚轮事件,并在它们知道滚动错误的元素时调用它们的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
}
相关问题