简体   繁体   English

使用 css 滚动捕捉时如何获取 window.scrollTop、ScrollY 或任何其他距离值

[英]How to get window.scrollTop, ScrollY or any other distance value when using css scroll snap

I am using css scroll snap to scroll through that are 100vh in height.我正在使用 css 滚动快照来滚动高度为 100vh。 The scroll snap works beautifully.滚动快照效果很好。

That said I need to determine how far the site visitor has scrolled for a few different reasons.也就是说,我需要确定网站访问者由于几个不同的原因滚动了多远。

I have tried:我努力了:

let wrapper = document.getElementById('landing-page-wrapper');
console.log(wrapper.offsetTop);
console.log(window.scrollY);

I have also tried window.scrollTop, wrapper.scrollTop and more.我也尝试过 window.scrollTop、wrapper.scrollTop 等。

Here is a Codepen of what I am seeing这是我所看到的Codepen

How can I know the distance scrolled while using 100vh sections and css scroll-snap我如何知道使用 100vh 部分和 css 滚动快照时滚动的距离

TIA TIA

Based on your shared code, the reason why window.onscroll does not work as expected is because neither window nor document.body are overflowing vertically.根据您的共享代码, window.onscroll无法按预期工作的原因是因为windowdocument.body都没有垂直溢出。 Only the element that is overflowing will fire the scroll event, and in this case it is actually the element that matches the .box-wrapper selector.只有溢出的元素才会触发滚动事件,在这种情况下,它实际上是匹配.box-wrapper选择器的元素。

Therefore if you listen to the scroll event on that element, then you should be able to retrieve its vertical scroll position using event.currentTarget.scrollTop :因此,如果您收听该元素上的滚动事件,那么您应该能够使用event.currentTarget.scrollTop检索其垂直滚动 position :

document.querySelector(".box-wrapper").addEventListener("scroll", (e) => {
  console.log(e.currentTarget.scrollTop);
});

See proof-of-concept example:请参阅概念验证示例:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM