我试图转换一个函数,一旦用户滚过一个截面元素就增加一个计数器,我得到了大部分工作,但不知何故,在我传递第一个截面元素后增量变得坚固,是我的函数来确定偏移量每个元素的顶部总错了?
我还认为与jQuery解决方案相比,vanilla JS版本输出的像素略有不同。
jQuery的: codePen
// scoll to next section and back to top
var $scrollSection = $('section');
var $scrollTrigger = $('.section_trigger');
var nextSection = 0;
// turn arrow when scrolled to footer
$(window).scroll(function() {
//console.log('current distance to top ' + $('body').scrollTop());
//console.log('element distance to top ' + $($scrollSection[nextSection]).offset().top);
while ($('body').scrollTop() > $($scrollSection[nextSection]).offset().top) {
nextSection++;
console.log('current section' + nextSection);
}
});
JS: CodePen
const sectionElements = document.getElementsByTagName('section');
const scrollTrigger = document.querySelector('.section_trigger');
let nextSection = 0;
let scrollObject = {};
const element = sectionElements[nextSection];
// calculate an elements distance to top
const elemRect = element.getBoundingClientRect(),
offset = elemRect.top - document.body.scrollTop;
// function to get the current distance to top
window.onscroll = getScrollPosition;
function getScrollPosition(){
scrollObject = {
x: window.pageXOffset,
y: window.pageYOffset
}
}
window.addEventListener('scroll', function() {
// console.log('current distance to top ' + scrollObject.y);
// console.log('element distance to top ' + offset);
if (scrollObject.y > offset) {
nextSection += 1;
console.log('current section' + nextSection);
}
});
非常感谢
答案 0 :(得分:1)
我相信这就是你要找的东西:
const sectionElements = document.getElementsByTagName('section');
const scrollTrigger = document.querySelector('.section_trigger');
let nextSection = 0;
let scrollObject = {};
// function to get the current distance to top
window.onscroll = getScrollPosition;
function getScrollPosition(){
scrollObject = {
x: window.pageXOffset,
y: window.pageYOffset
}
}
window.addEventListener('scroll', function() {
let element = sectionElements[nextSection];
// calculate an elements distance to top
let elemRect = element.getBoundingClientRect();
let offset = document.body.scrollTop + elemRect.top;
// console.log('current distance to top ' + scrollObject.y);
// console.log('element distance to top ' + offset);
if (scrollObject.y > offset) {
nextSection += 1;
console.log('current section' + nextSection);
}
});