- 监听文档滚动事件:
在JavaScript中,可以使用
window.addEventListener('scroll', callback)
来监听文档的滚动事件,其中callback
是滚动时执行的函数。
- 判断是否滚动到页面底部一定距离:
可以通过比较
document.documentElement.scrollTop + window.innerHeight
(当前滚动位置加上视口高度)与document.documentElement.scrollHeight
(文档总高度)的差值是否小于某个设定的距离来判断。
- 关键代码片段:
window.addEventListener('scroll', function () {
const distanceToBottom = document.documentElement.scrollHeight - (document.documentElement.scrollTop + window.innerHeight);
if (distanceToBottom < 100) { // 假设距离底部100像素时触发
fetch('your - api - url')
.then(response => response.json())
.then(data => {
// 处理获取到的新数据,例如添加到页面中
console.log(data);
});
}
});