首頁  >  文章  >  web前端  >  當內部元素到達末尾時如何防止父元素滾動傳播?

當內部元素到達末尾時如何防止父元素滾動傳播?

Barbara Streisand
Barbara Streisand原創
2024-10-28 07:17:30805瀏覽

How to Prevent Parent Element Scroll Propagation When Inner Element Reaches End?

內部元素到達結束時阻止父元素滾動傳播

在固定div內滾動且溢出時,經常會遇到滾動request 被父元素“接管”,導致外部文件捲動到工具箱之外。可以透過阻止滾動事件傳播來停止此行為。

雖然 jQuery event.stoppropagation() 方法看起來像是一個合適的解決方案,但它無法完全阻止傳播。相反,更有效的方法是在 jQuery 中處理 mousewheel 事件。

mousewheel 事件提供了一個wheelDelta 屬性,用於指示滾動的方向和數量。透過檢查wheelDelta值,您可以確定滾動是否超出內部div的頂部或底部。

為了相容於Internet Explorer,需要使用originalEvent.detail屬性,該屬性具有與其他瀏覽器。將細節乘以 -40 可以標準化所有瀏覽器中的值。

提供的jQuery 程式碼示範了這種方法:

<code class="javascript">$(document).on('DOMMouseScroll mousewheel', '.Scrollable', function(ev) {
    // Get the div's scroll properties
    var $this = $(this),
        scrollTop = this.scrollTop,
        scrollHeight = this.scrollHeight,
        height = $this.innerHeight(),
        delta = (ev.type == 'DOMMouseScroll' ?
            ev.originalEvent.detail * -40 :
            ev.originalEvent.wheelDelta);

    // Determine if the scroll would exceed the edge conditions
    if (delta > 0 && -delta > scrollHeight - height - scrollTop) {
        // Scrolling down past the bottom, prevent and scroll to bottom
        $this.scrollTop(scrollHeight);
        ev.stopPropagation();
        ev.preventDefault();
        return false;
    } else if (delta < 0 && delta > scrollTop) {
        // Scrolling up past the top, prevent and scroll to top
        $this.scrollTop(0);
        ev.stopPropagation();
        ev.preventDefault();
        return false;
    }
});</code>

透過處理滑鼠滾輪事件並在到達邊緣時阻止滾動傳播內部div的,可以有效防止父元素滾動的不良行為,並將滾動保持在所需的容器內。

以上是當內部元素到達末尾時如何防止父元素滾動傳播?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn