使用Javascript测量滚动速度并触发事件。

3

当窗口滚动速度超过某个值时,我希望触发一个事件。我找到了一些代码可以帮助测量速度,但是我无法弄清楚为什么当速度超过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个回答

2
你正在连续调用 checkScrollSpeed,当第二次调用时 delta 为0。要么移除 console.log,要么将 delta 赋值给某个变量并在日志和条件中使用该变量。

1

我认为这是因为您在第一次在console.log中调用checkScrollSpeed()和在if语句中调用之间有一点延迟。您可以尝试仅调用一次并保存值以供您的console.logif语句使用。对我来说,这个解决方案有效:

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() {
  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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接