javascript - 如何获得窗口高度和滚动位置之间的差异?
问题描述
我想做自定义无限滚动,所以当我尝试这个时
const scrollPosition = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
if(window.innerHeight-scrollPosition >100){
console.log("end")
}
但它不起作用。
解决方案
如果您想知道何时距离结束 100 像素,那么您可以获取当前元素 scrollHeight 并减去父元素高度,然后减去额外的 100。
现在将其与 parentElements scrollTop 进行比较,如果它更大,那么您的滚动条就在这个 100px 部分内。
下面的例子..如果你向下滚动直到你在结束的 100 像素内,背景将变为银色。
document.body.innerText =
new Array(400).fill('Scroll me down, ').join('');
window.addEventListener('scroll', (e) => {
const body = document.body;
const parent = body.parentElement;
const pixelsFromBottom =
body.scrollHeight -
parent.clientHeight
-100;
body.classList.toggle('inf'
,parent.scrollTop > pixelsFromBottom);
});
.inf {
background-color: silver;
}
这不仅适用于 Body,还适用于任何子控件,下面我创建了一个页眉页脚,以及一个可滚动区域。
const scroller = document.querySelector('main');
const target = document.querySelector('.content');
target.innerText =
new Array(400).fill('Scroll me down, ').join('');
scroller.addEventListener('scroll', (e) => {
const body = target;
const parent = body.parentElement;
const pixelsFromBottom =
body.scrollHeight -
parent.clientHeight
-100;
parent.classList.toggle('inf'
,parent.scrollTop > pixelsFromBottom);
});
html, body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
background-color: cyan;
overflow: hidden;
}
body {
display: flex;
flex-direction: column;
}
main {
position: relative;
flex: auto;
overflow-y: scroll;
background-color: white;
}
.content {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.inf {
background-color: silver;
}
<header>This is a header</header>
<main><div class="content">main</div></main>
<footer>This is the footer</footer>
推荐阅读
- java - 将图像动态应用到菜单项
- php - 创建没有数据库表的自定义控制器
- angular - 有没有办法将 {{}} 参数传递给点击内的函数?
- javascript - 如何使用 jquery/javascript 将每个标题转换为永久链接
- haskell - 如何在 Haskell 中派生多个 Functor 实例?
- dask - 读取 csv 文件时禁用错误
- algorithm - 基本情况 D[0] 如何是一个,其中 D[n] 是 n 可以表示为 1、3、4 之和的方式数?
- android - 如何通过检索 Firebase 数据来填充列表适配器?
- java - java.lang.NoClassDefFoundError 库 apache poi netbeans
- database - MongoDB 中的连接错误“TransientTransactionError”