javascript - 试图获得累积的垂直滚动距离
问题描述
我正在尝试获取用户的累积滚动距离。如果他们改变滚动方向,则累积滚动重置为他们最后一次滚动的距离,否则(如果方向相同)累积滚动距离增加。我想要这个图,以便只有在用户滚动超过几个像素后,我才能在我的网站上隐藏和显示导航栏。否则太敏感了。
到目前为止,我的代码并没有按我预期的方式工作。有时,尽管滚动方向保持不变,但累积滚动值并没有增加,而在其他时候开始正常工作。如果有人能阐明我在这里做错了什么,我将不胜感激。
const showHideHeader = (function(){
const doc = document.documentElement;
const w = window;
const contactInfo = document.querySelector(".contact-info");
let prevScroll = w.scrollY || doc.scrollTop;
let curScroll;
let direction = 0;
let prevDirection = 0;
let cumulativeScroll = 0;
let distanceScrolled = 0;
const checkScroll = function() {
curScroll = w.scrollY || doc.scrollTop;
distanceScrolled = Math.abs(curScroll - prevScroll);
console.log(`distance scrolled is ${distanceScrolled}`);
if (curScroll > prevScroll) {
direction = 2;
}
else if (curScroll < prevScroll) {
direction = 1;
}
if (direction === prevDirection) {
cumulativeScroll += distanceScrolled;
} else if (direction !== prevDirection) {
cumulativeScroll = distanceScrolled;
}
console.log(`cumulative scroll is ${cumulativeScroll}`);
console.log(`direction is ${direction}`);
if (cumulativeScroll > 10) {
toggleHeader(direction, curScroll);
}
prevScroll = curScroll;
};
const toggleHeader = function(direction, curScroll) {
if (direction === 2 && curScroll > 85) {
header.classList.add("home-hide");
contactInfo.classList.add("hide");
prevDirection = direction;
} else if (direction === 1) {
header.classList.remove("home-hide");
contactInfo.classList.remove("hide");
prevDirection = direction;
}
};
window.addEventListener('scroll', checkScroll);
})();
解决方案
推荐阅读
- javascript - 当我去下个月时,日历中缺少几个月
- javascript - 使用 php sdk 显示 Facebook 登录按钮
- java - 找不到密钥库文件
- performance - 在 Angular 6+ 应用程序中检测慢速互联网
- go - 在 Ubuntu 16.04 中出现 GOPATH 错误“go: cannot use path@version syntax in GOPATH mode”
- python - 如何将具有多个键值的字典数组转换为具有单个键值的字典?
- php - 为什么我的 SAW(简单加法加权)无法显示结果?
- java - JPA Criteria API:遍历列表并创建谓词
- python - 按可变数量移动矩阵中的行
- keras - Keras 中的零填充是否需要内存?