gpt4 book ai didi

javascript - 将滚动经过元素时增加计数器的 jQuery 函数转换为普通 Js

转载 作者:行者123 更新时间:2023-12-03 04:30:15 25 4
gpt4 key购买 nike

我正在尝试转换一个函数,一旦用户滚动经过一个部分元素,该函数就会增加计数器,我的大部分工作都正常工作,但不知何故,在我通过第一个部分元素后,增量变得疯狂,这是我确定偏移量的函数每个元素的顶部总共错误吗?

我还发现,与 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);
}

});

非常感谢

最佳答案

我相信这就是您正在寻找的:

CodePen

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);
}
});

关于javascript - 将滚动经过元素时增加计数器的 jQuery 函数转换为普通 Js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43523211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com