js怎么做无限滚动
在JavaScript中,可以使用以下方法实现无限滚动:
- 监听滚动事件:使用
addEventListener方法监听滚动事件,当滚动到页面底部时触发加载新内容的函数。
window.addEventListener('scroll', function() {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
// 这里触发加载新内容的函数
}
});
- 发送异步请求获取新内容:在滚动到页面底部时,发送异步请求获取新的内容。可以使用
XMLHttpRequest对象或者fetch函数来发送请求。
function loadNewContent() {
// 发送异步请求获取新内容
fetch('https://example.com/new-content')
.then(response => response.json())
.then(data => {
// 处理获取的新内容
});
}
- 添加新内容到页面:在获取到新的内容后,将新内容添加到页面中。可以使用
appendChild方法将新的DOM元素添加到页面中。
function loadNewContent() {
fetch('https://example.com/new-content')
.then(response => response.json())
.then(data => {
// 处理获取的新内容
data.forEach(item => {
const newElement = document.createElement('div');
newElement.innerText = item;
document.body.appendChild(newElement);
});
});
}
通过以上步骤,就可以实现无限滚动效果。每当滚动到页面底部时,就会加载新的内容并添加到页面中
原文地址: https://www.cveoy.top/t/topic/iygO 著作权归作者所有。请勿转载和采集!