Parallax effect make elements follow scroll with delay

 ̄綄美尐妖づ 提交于 2019-12-01 14:45:02

Here's DEMO
Its actually uses debounce/throttle effect . When you scroll up/down you shouldn't modify/animate DOM element directly because scroll event can fire up at high rate in which case animation DOM element can behave weird so to avoid this you can use windowAnimationFrame or setTimeout to throttle/debounce event

throttle with setTimeout taken from Source

Function.prototype.debounce = function(threshold){
    var callback = this;
    var timeout;
    return function() {
        var context = this, params = arguments;
        window.clearTimeout(timeout);
        timeout = window.setTimeout(function() {
            callback.apply(context, params);
        }, threshold);
    };
};

function animLoop(){
 ....
}
var test=animLoop.deboune(50);
$(window).on('scroll',test);

Window.requestAnimationFrame() MDN Scource

The Window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint.

var last_known_scroll_position = 0;
var ticking = false;

function doSomething(scroll_pos) {
  // do something with the scroll position
}

window.addEventListener('scroll', function(e) {
  last_known_scroll_position = window.scrollY;
  if (!ticking) {
    window.requestAnimationFrame(function() {
      doSomething(last_known_scroll_position);
      ticking = false;
    });
  }
  ticking = true;
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!