繁体   English   中英

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

[英]background position issue in parallax scrolling in javascript

我有这种常见的视差滚动模式,使用普通的javascript,使用自定义数据属性并在相反的方向滚动背景图像。

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();

    });

}

问题是此代码计算Ypos变量并将其分配给后台position-y属性。 实际上它会在你开始滚动之前覆盖设置为50%的css。 因此,一旦开始滚动,图像就会从中心向下移动。 我已经包含了一个codepen来查看问题。

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

有没有办法将yPos变量添加到初始化的背景位置50%50%,这意味着将它变为50%50%+ ypos而不是50%ypos。

谢谢。

我改变了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}%`;

您可以在此处查看更改:

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

暂无
暂无

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

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