我有一个设置了overflow
为scroll
的div
层。
当滚动到div
的底部时,我想要运行一个函数。
我有一个设置了overflow
为scroll
的div
层。
当滚动到div
的底部时,我想要运行一个函数。
要在React/JSX中执行相同操作,这里是代码片段。
export const scrolledToEnd = event => {
const container = event.target;
if (container.offsetHeight + container.scrollTop >= container.scrollHeight) {
return true;
}
return false;
};
在你的组件中添加以下代码
<Component onScroll={scrolledToEnd}>
由于在一些旧版本的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();
}
});
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
}
}
好的,现在针对你的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
}
}
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>
)