简体   繁体   English

javascript中视差滚动的背景位置问题

[英]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. 我有这种常见的视差滚动模式,使用普通的javascript,使用自定义数据属性并在相反的方向滚动背景图像。

HTML: 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: 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: 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. 问题是此代码计算Ypos变量并将其分配给后台position-y属性。 Actually it overrides the css which is set to 50% before you start scrolling. 实际上它会在你开始滚动之前覆盖设置为50%的css。 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. 我已经包含了一个codepen来查看问题。

https://codepen.io/anon/pen/pLvjqR 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. 有没有办法将yPos变量添加到初始化的背景位置50%50%,这意味着将它变为50%50%+ ypos而不是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. 我改变了3 - > .02和javascript的速度,你必须从50%开始并减少这个百分比而不是以像素为单位应用值。

// 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 https://codepen.io/anon/pen/mxyVBV

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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