[英]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}%`;
您可以在此處查看更改:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.