测量滚动速度Javascript和触发事件

时间:2019-01-03 09:06:23

标签: javascript

当窗口滚动速度超过某个值时,我想触发一个事件。我找到了一些有助于测量速度的代码,但无法弄清楚为什么速度超过150时不会触发if语句。我们将不胜感激。

const checkScrollSpeed = (function(settings){
    settings = settings || {};

    let lastPos, newPos, timer, delta, 
        delay = settings.delay || 50;

    function clear() {
        lastPos = null;
        delta = 0;
    }

    clear();

    return function(){
        newPos = window.scrollY;
        if ( lastPos != null ){ // && newPos < maxScroll 
            delta = newPos -  lastPos;
        }
        lastPos = newPos;
        clearTimeout(timer);
        timer = setTimeout(clear, delay);
        return delta;
    };
})();

const container = document.querySelector('#container');

window.addEventListener('scroll', function() {
    console.log(checkScrollSpeed());
    if (checkScrollSpeed() > 150) {
        console.log('150+')
        container.classList.add('red');
    }
});
#container {
  width: 75%;
  height: 170vh;
  background-color: yellow;
}
#container.red {
  background-color: red !important;
}
<div id="container"></div>

2 个答案:

答案 0 :(得分:2)

我认为这是因为您在第一次在checkScrollSpeed()中调用console.log到在if语句中调用console.log之间存在一些延迟。您可以尝试仅调用一次并保存ifconst checkScrollSpeed = (function(settings) { settings = settings || {}; let lastPos, newPos, timer, delta, delay = settings.delay || 50; function clear() { lastPos = null; delta = 0; } clear(); return function() { newPos = window.scrollY; if (lastPos != null) { // && newPos < maxScroll delta = newPos - lastPos; } lastPos = newPos; clearTimeout(timer); timer = setTimeout(clear, delay); return delta; }; })(); const container = document.querySelector('#container'); window.addEventListener('scroll', function() { var speed = checkScrollSpeed(); console.log(speed); if (speed > 150) { console.log('150+'); container.classList.add('red'); } });语句的值。此解决方案对我有用:

#container {
  width: 75%;
  height: 170vh;
  background-color: yellow;
}

#container.red {
  background-color: red !important;
}
<div id="container"></div>
goPlot

答案 1 :(得分:2)

您要连续调用checkScrollSpeed,并且第二次调用增量为0时,请删除console.log或将增量分配给某个变量,然后将其用于记录日志和条件。