Движение элементов при скролле
Есть код, который двигает елементы в бэкграунде при движении мышью. Как сделать так, чтобы при скролле они меняли свое положение. То есть, едешь вниз - они чутка вверх плывут, едешь вверх - они вниз. Ссылка на код codepen
<script>
(function() {
document.addEventListener("mousemove", parallax);
const elem = document.querySelector("#block");
function parallax(e) {
let _w = window.innerWidth/2;
let _h = window.innerHeight/2;
let _mouseX = e.clientX;
let _mouseY = e.clientY;
let _depth1 = `${5 - (_mouseX - _w) * 0.0007}% ${45 - (_mouseY - _h) * 0.0011}%`;
let _depth2 = `${25 - (_mouseX - _w) * 0.0006}% ${-5 - (_mouseY - _h) * 0.002}%`;
let _depth3 = `${35 - (_mouseX - _w) * 0.0009}% ${110 - (_mouseY - _h) * 0.006}%`;
let _depth4 = `${50 - (_mouseX - _w) * 0.0008}% ${50 - (_mouseY - _h) * 0.004}%`;
let _depth5 = `${70 - (_mouseX - _w) * 0.0005}% ${90 - (_mouseY - _h) * 0.007}%`;
let _depth6 = `${95 - (_mouseX - _w) * 0.0005}% ${50 - (_mouseY - _h) * 0.0013}%`;
let x = `${_depth1}, ${_depth2}, ${_depth3}, ${_depth4}, ${_depth5}, ${_depth6}`;
elem.style.backgroundPosition = x;
}
})();
</script>
#block{
width: 100%;
height: 100vh;
background-image: url(photo1.png),
url(photo2.png),
url(photo3.png),
url(photo4.png),
url(photo5.png),
url(photo6.png);
background-repeat: no-repeat;
background-position: center;
}
Ответы (1 шт):
Автор решения: Aleksandr Belous
→ Ссылка
Написал функцию, которая добавляет параллакс эффект любому блоку с background-image
const setParallax = (selector) => {
const scrollElement = document.querySelector(selector)
const scrolled = scrollElement.getBoundingClientRect().top
scrollElement.style.backgroundPosition = `0 ${0 - (scrolled * .25) + 'px'}`
}
window.addEventListener('scroll', () => setParallax('.js-parallax'))
.section {
font-family: sans-serif;
height: 50vh;
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(0,0,0,0.13);
}
.bg {
color: white;
background-image: url("https://relationary.com/wp-content/uploads/2019/10/pexel-nature-bg.jpeg")
}
<section class="section">
<h2>Section 1</h2>
</section>
<section class="section bg js-parallax">
<h2>Section 2</h2>
</section>
<section class="section">
<h2>Section 3</h2>
</section>