我正在学习如何在guide之后创建滚动视差效果。到目前为止一直很好,但后来我意识到我的背景位置设置为50%'(中心)。因此,当我运行我的js时,背景位置单位从%变为 px ,因此它的位置不符合我的预期。
如何编写代码以使背景位置以百分比变化?
以下是代码:
window.addEventListener('scroll', function(){
var scrollPosition = window.pageYOffset;
var bgParallax = document.getElementsByClassName('parallax')[0];
var limit = bgParallax.offsetTop + bgParallax.offsetHeight;
if (scrollPosition > bgParallax.offsetTop && scrollPosition <= limit){
bgParallax.style.backgroundPositionY = scrollPosition / 2 + 'px';
}else{
bgParallax.style.backgroundPositionY = '0';
}
});
&#13;
body{
margin:0px;
padding:0px;
height:600px;
}
.parallax{
width:100%;
height:300px;
background-color:red;
background-image:url('http://68.media.tumblr.com/9c811fb09ae9fe61e3bbcb1d7f0c3724/tumblr_o9489fIsmH1qhttpto3_1280.png');
background-position:center;
}
&#13;
<div class='parallax'></div>
&#13;
这是 CODEPEN
PPD:我无法改变我的HTML或CSS,我需要用纯JavaScript来解决这个问题。答案 0 :(得分:3)
这样的东西?
它本质上是相同的,只是从50%而不是0px开始,并在向下滚动时减去,具体取决于图像应移动的距离。 (在这种情况下为10%,因此backgroundPositionY
从40%到50%不等)
window.addEventListener('scroll', function(){
var scrollPosition = window.pageYOffset;
var bgParallax = document.getElementsByClassName('parallax')[0];
var limit = bgParallax.offsetTop + bgParallax.offsetHeight;
if (scrollPosition > bgParallax.offsetTop && scrollPosition <= limit){
bgParallax.style.backgroundPositionY = (50 - 10*scrollPosition/limit) + '%';
}else{
bgParallax.style.backgroundPositionY = '50%';
}
});
&#13;
body{
margin:0px;
padding:0px;
height:600px;
}
.parallax{
width:100%;
height:300px;
background-color:red;
background-image:url('http://68.media.tumblr.com/9c811fb09ae9fe61e3bbcb1d7f0c3724/tumblr_o9489fIsmH1qhttpto3_1280.png');
background-position:center;
}
&#13;
<div class='parallax'></div>
&#13;