简体   繁体   中英

background position issue in parallax scrolling in javascript

I have this common pattern of parallax scrolling with plain javascript that uses custom data attributes and scrolls the background image in the oposite direction.

HTML:

  <header id="home" class="section" data-type="background" data-speed="3"></header>
  <section id="portfolio" class="section"></section>
  <section id="about" class="section"></section>
  <section id="contact" class="section"></section>

CSS:

  #home {
    background-color: grey;
    height: 100%;
    width: 100%;
    background-image: linear-gradient(to bottom, rgba(#000, 0.5), rgba(#000, 0.5)), url("../bg.jpg");
    background-attachment: fixed;
    background-repeat: repeat;
    background-position: 50%;
    background-size: cover;
    position: relative;
  }

JAVASCRIPT:

{

    function parallax() {
        Array.from(document.querySelectorAll('*[data-type="background"]')).forEach(e => {

            let yPos = -(window.pageYOffset / e.dataset.speed);

            var coords = `50% ${yPos}px`;

            e.style.backgroundPosition = coords;
        });
    }

    document.addEventListener('scroll', function () {

        parallax();

    });

}

The issue is that this code calculates the Ypos variable and assigns it to the background position-y property. Actually it overrides the css which is set to 50% before you start scrolling. As a result the image goes from the center to the bottom once you start scrolling. I have included a codepen to see the problem.

https://codepen.io/anon/pen/pLvjqR

Is there any way to add the yPos variable to the initialized background position 50% 50%, which means make it 50% 50%+ypos instead of 50% ypos.

Thanks.

I changed the speed of 3 -> .02 and javascript, you have to start at 50% and reduce this percentage rather than applying values in pixels.

// let yPos = -(window.pageYOffset / e.dataset.speed);
let yPos = (e.getBoundingClientRect().top - window.pageYOffset) * e.dataset.speed + 50;

// var coords = `50% ${yPos}px`;
var coords = `50% ${yPos}%`;

You can view changes here :

https://codepen.io/anon/pen/mxyVBV

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM