我正在尝试在页面的某个部分内设置一个视差效果div,麻烦的是我很难定位所以它只显示在父节上(下面代码中的id'foo') )页面。我怎样才能做到这一点?
HTML
<section>
<p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p>
</section>
<article id="foo">
<div id="parallax"></div>
</article>
<section>
<p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p>
</section>
CSS
#parallax {
background: url('http://lorempixel.com/output/cats-q-c-220-129-8.jpg') transparent no-repeat;
width:100%;
height:200px;
z-index: 20;
right: -73%;
position: fixed;
}
article {
height: 200px;
background-color: aliceblue;
}
section {
background-color: black;
color: white;
padding: 1%;
}
JS
$(window).scroll(function(){
function parallax(){
if($(window).scrollTop() < $('#foo').offset().top){
var parallaxLayer = document.getElementById('parallax');
parallaxLayer.style.top = ((window.pageYOffset / 4) - 400)+'px';
}else{
}
}
window.addEventListener("scroll", parallax, false);
});
答案 0 :(得分:0)
这就是你想要做的吗? 我在codepen中覆盖了你的代码。 希望它会有所帮助。 的 codepen.io/jaminpie/pen/Lnjtc 强>
答案 1 :(得分:0)
演示: http://jsfiddle.net/fdg9du90/show/
代码: http://jsfiddle.net/fdg9du90/
var w=$(window), bg = $('.bg');
w.scroll(function(e){
bg.css('top','-'+w.scrollTop()*.5+'px');
});
<强>解释强>
背景图像/ div设置为固定,jquery用于使事情变得更容易,我的意思是轻松附加事件,快速获取数据并以正确的形式等。在Windows上滚动事件时,滚动数据量窗口和halfed然后背景div移动该数量。