JavaScript:检测滚动结束

86

我有一个设置了overflowscrolldiv层。

当滚动到div的底部时,我想要运行一个函数。



2
请查看此JSFiddle演示 - Sender
截图损坏了。 - lilalinux
1
请查看此答案 scrollendevent 或者 MDN 文档 scrollend_event - Anil kumar
15个回答

0

要在React/JSX中执行相同操作,这里是代码片段。

export const scrolledToEnd = event => {
  const container = event.target;

  if (container.offsetHeight + container.scrollTop >= container.scrollHeight) {
    return true;
  }
  return false;
};

在你的组件中添加以下代码

<Component onScroll={scrolledToEnd}>

0

由于在一些旧版本的IE中,innerHeight无法正常工作,因此可以使用clientHeight

$(window).scroll(function (e){
    var body = document.body;    
    //alert (body.clientHeight);
    var scrollTop = this.pageYOffset || body.scrollTop;
    if (body.scrollHeight - scrollTop === parseFloat(body.clientHeight)) {
        loadMoreNews();
    }
});

0
我找到了一种获取滚动结束的方法:
let TheBody = document.getElementsByTagName("body"); // I choose the "body" element for my exemple
function OnScrolling(){                             // put this on a scrolling EVENT
let ScrollEnd = TheBody[0].scrollHeight - window.innerHeight; // this is the scroll end Pixel

    if (ScrollEnd.toFixed() == window.scrollY.toFixed()){
        //do stuff 
    }
}

0

好的,现在针对你的DIV或其他带有滚动条的元素,我在JavaScript中找到了这种方法:

let D = document.getElementById("D1"); // I gave "D1" as id to my div

    // this one is to calculate the scroll end Pixels
let Calc = D.scrollHeight - D.clientHeight;

function ScrollingInD1() {

    //this one is to calculate the scrolling percent while going through the <div> it can help for "Responsivity"
let percent = (D.scrollTop * 100) / Calc;

    if (D.scrollTop == Calc) {
        // do Stuffs
    }
}

0
这对我来说很有用,使用NextJS。希望能帮到你。
  • 从scrollHeight中减去1像素
function onScroll(e: any) {
    const scroll = e.target.offsetHeight + e.target.scrollTop
    const height = e.target.scrollHeight - 1

    if (scroll >= height){
        console.log("END REACHED")
    }
}

return (
    <div onScroll={onScroll}></div>
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接