Measure scroll velocity Javascript and trigger event

问题: I would like to trigger an event when the window scroll velocity goes above a certain value. I found some code that will help measure the velocity but I can't work out why...

问题:

I would like to trigger an event when the window scroll velocity goes above a certain value. I found some code that will help measure the velocity but I can't work out why the if statement is not triggered when the speed goes above 150. Any help would be greatly appreciated.

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>


回答1:

I think it's because you have a little delay between the first time you call checkScrollSpeed() in your console.log and then in your if statement. You can try to call it only once and save the value for your console.log and if statement. It works for me with this solution:

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>


回答2:

You are calling checkScrollSpeed in succession and when it's called the second time delta is 0. Either remove the console.log or assign delta to some variable and use that for logging and the condition.

  • 发表于 2019-01-04 17:01
  • 阅读 ( 212 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除