Witam,
W jaki sposób stworzyć sekcje z parallaxem, który jest sterowany poprzez właściwość margin-top? Napisałem cos takiego, ale wartość dla margin-top zostaje nałożona od razu, a powinna być zwiększana wraz z upływem scrolla.
window.ParallaxBG = (function() {
var images;
function init() {
images = [].slice.call(document.querySelectorAll('.js-parallax-bg'));
if (!images.length) {
return
}
Gator(window).on('scroll', doParallax);
Gator(window).on('resize', doParallax);
doParallax();
}
function getViewportHeight() {
var a = document.documentElement.clientHeight,
b = window.innerHeight;
return a < b ? b : a;
}
function getViewportScroll() {
if (typeof window.scrollY != 'undefined') {
return window.scrollY;
}
if (typeof pageYOffset != 'undefined') {
return pageYOffset;
}
var doc = document.documentElement;
doc = doc.clientHeight ? doc : document.body;
return doc.scrollTop;
}
function doParallax() {
var el, elOffset, elHeight,
offset = getViewportScroll(),
vHeight = getViewportHeight();
for (var i in images) {
el = images[i];
elOffset = el.offsetTop;
elHeight = el.offsetHeight;
if ((elOffset > offset + vHeight) || (elOffset + elHeight < offset)) {
continue;
}
el.style.marginTop = '-5' + Math.round((elOffset - offset) * 3 / 8) + 'px';
}
}
return {
init: init
}
})();
ParallaxBG.init();
Co ciekawe - efekt działa, gdy korzystam z background-position:
el.style.backgroundPosition = '50% ' + Math.round((elOffset - offset) * 3 / 8) + 'px';