问题
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