parallax impl
by rough cheap
HTML
<div id="status">
</div>
<div class="box">
<div class="item jparallax" data-parallax-scale="0.2">
</div>
</div>
<div class="box">
<div class="item jparallax">
</div>
</div>
<div class="box">
<div class="item jparallax"data-parallax-scale="0.7">
</div>
</div>
CSS
.box {
width: 300px;
height: 300px;
border: 1px solid grey;
margin-bottom: 800px;
overflow: hidden;
}
.item {
height: 100%;
background-image: url('https://wpdotorg.files.wordpress.com/2008/11/boat.jpg');
background-size: cover;
background-position: 50% 50%;
}
#status {
position: fixed;
top: 0;
right: 0;
}
JavaScript
(function() {
let ptargets = document.getElementsByClassName('jparallax');
let requestAnimationFrame =
window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
let state = document.querySelector('#status');
let viewHeight = document.documentElement.clientHeight;
Array.from(ptargets).forEach((target) => {
let scale = Number(target.getAttribute('data-parallax-scale') || 0.4);
let transScale = 1 + scale;
let vOffset = target.clientHeight * 0.5;
let imageOffset = target.clientHeight * scale;
let offsetHeight = viewHeight + target.clientHeight;
let offsetPosition = target.offsetTop + vOffset;
function scrollFunc() {
requestAnimationFrame((timestamp) => {
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
let scrollBottom = scrollTop + viewHeight;
let offsetTop = scrollTop - vOffset;
let offsetBottom = scrollBottom + vOffset;
if ((offsetBottom > offsetPosition) && (offsetPosition > offsetTop)) {
let moval = (imageOffset * (offsetHeight - (offsetPosition - offsetTop)) / offsetHeight) / transScale;
target.style.transform = 'scale(' + transScale + ')';
target.style.backgroundPosition = '50% ' + moval + 'px';
}
});
}
window.addEventListener('scroll', (e) => {
scrollFunc();
});
scrollFunc();
});
})();