实现说明
活动部件是函数 distanceToBottom。
for (let i = 1; i <= 50; i++) 承担全部的逐项处理。
使用要点
- 这是浏览器侧代码——
document、requestAnimationFrame在 Node 里解析不到。 - 直接运行文件,输出会带上标签,比如
scrollTop after clamp:、px from bottom:、loading flagged (same tick):——输出的每一行都能指回产生它的那次调用。
常见问题
「滚动位置判断列表触底」能在裸 Node.js 里跑吗?
不能——它用到 document、requestAnimationFrame。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。
主签名形如 function distanceToBottom()
核心语句
feed.addEventListener('scroll', () => {
if (distanceToBottom() < 200) feed.dataset.loading = 'true';
});
return feed.scrollHeight - scrolled;
requestAnimationFrame(() => {
console.log('loading flagged (after scroll event):', feed.dataset.loading === 'true');
});
代码示例
// Infinite-scroll readiness: how close is the viewport to the last row?
const feed = document.createElement('div');
feed.style.height = '300px';
feed.style.overflowY = 'scroll';
for (let i = 1; i <= 50; i++) {
feed.append(Object.assign(document.createElement('p'), { textContent: `row ${i}` }));
}
document.body.append(feed);
// scrollTop is the scroll position inside the list; scrollHeight is the
// full content height, clientHeight the visible viewport height.
function distanceToBottom() {
const scrolled = feed.scrollTop + feed.clientHeight;
return feed.scrollHeight - scrolled;
}
// Near the bottom, flag the list so a spinner or fetch can start.
feed.addEventListener('scroll', () => {
if (distanceToBottom() < 200) feed.dataset.loading = 'true';
});
// Assigning beyond the max clamps: scrollTop lands at the exact bottom edge.
feed.scrollTop = feed.scrollHeight;
console.log('scrollTop after clamp:', feed.scrollTop);
console.log('px from bottom:', distanceToBottom());
// Scroll events dispatch asynchronously: inside this same synchronous block
// the handler above has not run yet, so the flag is still unset.
console.log('loading flagged (same tick):', feed.dataset.loading === 'true');
// The scroll event fires as part of the next rendering update, before this
// frame callback runs — assert the flag there, not inline.
requestAnimationFrame(() => {
console.log('loading flagged (after scroll event):', feed.dataset.loading === 'true');
});