首页 > web前端 > js教程 > 正文

当内部元素到达末尾时如何防止父元素滚动传播?

Barbara Streisand
发布: 2024-10-28 07:17:30
原创
804 人浏览过

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!