0

Есть код, который двигает елементы в бэкграунде при движении мышью. Как сделать так, чтобы при скролле они меняли свое положение. То есть, едешь вниз - они чутка вверх плывут, едешь вверх - они вниз. Ссылка на код 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 ответ 1

0

Написал функцию, которая добавляет параллакс эффект любому блоку с 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>

6
  • спасибо за ответ, но тут суть в другом. codepen.io/hev1t/pen/KKXwRqV кинул на codepen этот код. Когда двигаешь мышкой то круги меняют свое положение, но надо сделать так, чтобы при скролле они меняли свое положение. То есть, едешь вниз - они чутка вверх плывут, едешь вверх - они вниз.
    – Nik8899
    1 дек 2021 в 14:31
  • Ну тогда вот так codepen.io/conarti/pen/LYzEBvj 1 дек 2021 в 16:05
  • Да, это оно! Спасибо )
    – Nik8899
    3 дек 2021 в 10:10
  • @Nik8899 отметьте как решение тогда) 3 дек 2021 в 11:20
  • да-да. только вот у меня генерируются ошибки в браузере при скролле и движению мышью: Uncaught TypeError: Cannot read properties of null (reading 'getBoundingClientRect') at getScrollFactor () at parallax () В чем может быть проблема?
    – Nik8899
    8 дек 2021 в 14:42

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.