簡體   English   中英

防止滾動模式框內容時滾動背景div

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

我有一個用於移動網站(iOS設備)的模式框,其中包含可滾動的內容。 最初的問題是在滾動模式內部的內容時,即使背景頁面也是可滾動的。 為了解決這個問題,我在打開模態框時向body標簽添加了“position:fixed”屬性,並在關閉模態框時將其刪除。

雖然這解決了初始滾動問題,但它會導致頁面在向body標簽添加“fixed property:”時滾動到頂部,並且一旦模態框關閉,頁面就會滾動到初始位置。

想要一個解決方案,以防止在將固定屬性添加到正文時將頁面滾動到頂部。

實現此目的的一種方法是監視觸摸和滾輪事件,並在知道它們將要滾動錯誤的元素時調用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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM