【问题标题】:How to capture the scroll event on a div to only scroll the top-most (by z-index) component如何捕获 div 上的滚动事件以仅滚动最顶部(按 z-index)组件
【发布时间】:2018-07-05 10:15:24
【问题描述】:

我已经说明了我在 Codepen 中描述的问题:https://codepen.io/anon/pen/KZOwdm?editors=1111

我的页面顶部有一个标题栏,页面顶部有一个固定位置 (position: fixed;)。

我页面的主要内容是一个带有margin-top 的可滚动列表,以确保它位于标题栏下方。点击这些项目中的任何一个都会带来一个slide-up,这是一个position: fixed; div 和z-index: 2;,它覆盖了从标题栏正下方到屏幕底部的整个页面。

我在滚动此slide-up 时遇到问题。我希望在上滑层上滚动只会滚动该 div 的内容,而不是整个页面(包括下面的内容)。当下面的内容很长时,这尤其令人沮丧。我看到的是,一旦上滑完成滚动,父 div 就会开始滚动。

在典型情况下,这种向上滑动是为了覆盖页面,有点像显示“新页面”。因此,当滚动上滑 div 时,我根本不希望父 div 进入等式。这里的第二个问题是,在移动设备上滚动似乎滚动父级,而不是向上滑动。这如何实现?

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    你需要两件事:

    1. overflow-y: scroll.slide-up 上以允许内容实际滚动
    2. height 小到足以让文本实际溢出 total height
      (不仅仅是可见的内容)。

    添加overflow-y: scroll 并将.slide-upheight 更改为calc(100% - 40px)(适用于top)在以下示例中展示了这一点:

    .tabs {
      position: fixed;
      top: 0;
      height: 40px;
      background: #f54;
      width: 100%;
      color: white;
      padding-left: 1em;
      display: flex;
      align-items: center;
      z-index: 2;
    }
    
    .slide-up {
      z-index: 2;
      top: 40px;
      position: fixed;
      background-color: #ffa000;
      height: calc(100% - 40px);
      width: 100px;
      left: 100px;
      color: #fff;
      overflow-y: scroll;
    }
    <div class='tabs'>
      <h5>Tabs</h5>
    </div>
    <div class='content'>
      <h5>Here is some random text to make this scroll</h5>
      <h5>This is the main content</h5>
      <h5>This is the main content</h5>
      <h5>This is the main content</h5>
      <h5>This is the main content</h5>
      <h5>This is the main content</h5>
      <h5>This is the main content</h5>
      <h5>This is the main content</h5>
      <h5>This is the main content</h5>
      <h5>This is the main content</h5>
      <h5>This is the main content</h5>
      <h5>This is the main content</h5>
      <h5>This is the main content</h5>
      <h5>This is the main content</h5>
      <h5>This is the main content</h5>
      <h5>This is the main content</h5>
    </div>
    <div class='slide-up'>
      <h5>Slide up content</h5>
      <h5>Slide up content</h5>
      <h5>Slide up content</h5>
      <h5>Slide up content</h5>
      <h5>Slide up content</h5>
      <h5>Slide up content</h5>
      <h5>Slide up content</h5>
      <h5>Slide up content</h5>
      <h5>Slide up content</h5>
      <h5>Slide up content end</h5>
    </div>

    希望这会有所帮助! :)

    【讨论】:

    • 您好,感谢您的回复!这似乎仍然是当我们到达终点时父母开始滚动的事实的受害者(至少在我的机器上)。可以帮忙吗?
    • 这是因为您将到达子内容的末尾,而父元素将获得“焦点”。如果确实有必要,可以通过 JavaScript 防止这种情况发生,尽管相当麻烦。 this question 中相当广泛地介绍了这样做 :)
    猜你喜欢
    • 2012-05-02
    • 2014-04-03
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    • 2022-10-13
    • 1970-01-01
    相关资源
    最近更新 更多