parallax div跳转到页面顶部

时间:2016-01-05 10:08:19

标签: javascript jquery parallax

我试图在div上创建一个视差效果但是当我开始滚动时它会跳到页面的顶部。最高值立即变为0

HTML

<div class="container">
<div class="top">
</div>
<div class="middle">
</div>
<div class="slider" id="rowSlider">
</div>
<div class="content">
</div>
</div>

JS

function parallax(){
    var prlx_lyr_1 = document.getElementById('rowSlider');
    prlx_lyr_1.style.top = -(window.pageYOffset / 2)+'px';
}
window.addEventListener("scroll", parallax, false);

CSS

.container{width:100%;}
.top{position:fixed; top:0; left:0; width:100%; z-index:1; background:#000; height:50px;}
.middle{width:100%; height:150px; background:red; width:100%; position:relative; z-index:2; margin-top:50px;}
.slider{width:100%; position:fixed; height:200px; background:orange; left:0; top:200px; z-index:3;}
.content{width:100%; position:relative; z-index:4; height:200px; background:blue; margin-top:400px;}

JSFIDDLE DEMO

1 个答案:

答案 0 :(得分:1)

感谢dann:

.slider的初始位置是200px。解决方案是:

prlx_lyr_1.style.top = (200-(window.pageYOffset / 2))+'px';

https://jsfiddle.net/rd9kot8p/3/