Parallax effect make elements follow scroll with delay

二次信任 提交于 2019-12-04 02:24:12

问题


I am trying to replicate this site: www.adidas.co.uk/climazone. The elements seem to only move slightly after the user scrolls. How can I achieve this? Thank you!


回答1:


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


来源:https://stackoverflow.com/questions/37502075/parallax-effect-make-elements-follow-scroll-with-delay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!