如何使用vanilla javascript判断元素的顶部或底部何时滚动到页面顶部



我有一个网页,上面有两个100%高度的div,就像这样。。。

<style>
html, body{
height: 100%;
width: 100%;
margin: 0;
overflow: hidden;
}
#wrapper{
height:100%;
width:100%;
overflow: auto;
}
.scroll-item{
height: 100%;
width: 100%;
}
</style>
...
<body>
<div id="wrapper">
<div id="test1"
class="scroll-item">Simple Test 1</div>
<div id="test2"
class="scroll-item">Simple Test 2</div>
</div>
</body>

现在我想"选择";当前滚动到的元素。这意味着元素的顶部已经到达浏览器的顶部,但底部还没有。这就是我感到困惑的地方,这里是JS。。。

<script type="module">
const body = document.getElementsByTagName("body")[0];
const handleScroll = function(info){
const items = body.getElementsByClassName("scroll-item");
for(let i = 0; i < length; i++){
const item = items[i];
// TODO How do I tell if it is there
}
}
body.addEventListener("wheel",handleScroll);
</script>

我试过使用边界框,但我不知道如何使其正确工作。

如何判断元素的顶部或底部何时到达浏览器的顶部(给定导航栏的可能偏移量(?

您可以使用getBoundingClientRect((。它为您提供了包含元素大小和坐标的DOMRect对象。

...
if (item.getBoundingClientRect().top < 0) {
// items top has reached beyond window top
}
if (item.getBoundingClientRect().bottom > window.innerHeight) {
// items bottom is beyond window bottom
}
...

有关高级用法,请参见IntersectionObserver,它检测视口内的图元可见性。

使用包装器获取当前位置并侦听滚动事件,此外,最好侦听滚动,而不是滚轮事件。

// Use the wrapper to get and listen scroll
const wrapper = document.querySelector('#wrapper')
const handleScroll = function(event) {
const top = wrapper.scrollTop;
document.querySelectorAll('.scroll-item').forEach((item, index) => {
// Calculate item bottom position
const bottom = item.offsetTop + item.offsetHeight;
// Is the scroll between item top and bottom?
if(top >= item.offsetTop && top < bottom) {
console.log(`Item ${index} is active`);
}
});
}
// scroll event is more accurate than wheel
wrapper.addEventListener("scroll", handleScroll);
html, body{
height: 100%;
width: 100%;
margin: 0;
overflow: hidden;
}
#wrapper{
height:100%;
width:100%;
overflow: auto;
}
.scroll-item{
height: 100%;
width: 100%;
}
<body>
<div id="wrapper">
<div id="test1"
class="scroll-item">Simple Test 1</div>
<div id="test2"
class="scroll-item">Simple Test 2</div>
</div>
</body>

最新更新