首页 > 解决方案 > 试图获得累积的垂直滚动距离

问题描述

我正在尝试获取用户的累积滚动距离。如果他们改变滚动方向,则累积滚动重置为他们最后一次滚动的距离,否则(如果方向相同)累积滚动距离增加。我想要这个图,以便只有在用户滚动超过几个像素后,我才能在我的网站上隐藏和显示导航栏。否则太敏感了。

到目前为止,我的代码并没有按我预期的方式工作。有时,尽管滚动方向保持不变,但累积滚动值并没有增加,而在其他时候开始正常工作。如果有人能阐明我在这里做错了什么,我将不胜感激。

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

})();

标签: javascriptscrolldistance

解决方案


推荐阅读