【问题标题】:how to get difference between window height and scroll location?如何获得窗口高度和滚动位置之间的差异?
【发布时间】:2021-07-15 12:41:37
【问题描述】:

我想做自定义无限滚动,所以当我尝试这个时

 const scrollPosition = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
if(window.innerHeight-scrollPosition >100){
console.log("end")
}

但它不起作用。

【问题讨论】:

    标签: javascript typescript window infinite-scroll angular10


    【解决方案1】:

    如果您想知道何时距离终点还有 100 像素,那么您可以获取当前元素的 scrollHeight 并减去父元素的高度,然后再减去额外的 100。

    现在将它与 parentElements scrollTop 进行比较,如果它更大,那么你的滚动条就在这个 100 像素的部分内..

    下面的示例..如果向下滚动到距离末端 100 像素以内,背景将变为银色。

    document.body.innerText =
      new Array(400).fill('Scroll me down, ').join('');
    
    window.addEventListener('scroll', (e) => {
      const body = document.body;
      const parent = body.parentElement;
      const pixelsFromBottom = 
        body.scrollHeight -
        parent.clientHeight
        -100;
      body.classList.toggle('inf'
        ,parent.scrollTop > pixelsFromBottom);
    });
    .inf {
      background-color: silver;
    }

    这不仅适用于 Body,还适用于任何子控件,下面我创建了一个页眉页脚,以及一个可滚动区域。

    const scroller = document.querySelector('main');
    const target = document.querySelector('.content');
    
    target.innerText =
      new Array(400).fill('Scroll me down, ').join('');
    
    scroller.addEventListener('scroll', (e) => {
      const body = target;
      const parent = body.parentElement;   
      const pixelsFromBottom = 
        body.scrollHeight -
        parent.clientHeight
        -100;
      parent.classList.toggle('inf'
        ,parent.scrollTop > pixelsFromBottom);
    });
    html, body {
      height: 100%;
      width: 100%;
      padding: 0;
      margin: 0;
      background-color: cyan;
      overflow: hidden;
    }
    
    body {
      display: flex;
      flex-direction: column;
    }
    
    main {
      position: relative;
      flex: auto;
      overflow-y: scroll;
      background-color: white;
    }
    
    .content {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }
    
    .inf {
      background-color: silver;
    }
    <header>This is a header</header>
    <main><div class="content">main</div></main>
    <footer>This is the footer</footer>

    【讨论】:

    • @JohnDoe 我添加了一个使用固定页眉和页脚的示例。
    猜你喜欢
    • 2021-01-12
    • 2010-09-23
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 2013-04-03
    相关资源
    最近更新 更多