【发布时间】:2015-08-15 11:00:20
【问题描述】:
我试图让一些 div 以与页面其余部分不同的速度滚动以创建视差效果。
这是我的 JS 和 HTML:
<div class="container">
<div class="background">
<img src="http://placehold.it/150x150/" />
</div>
<div class="background">
<img src="http://placehold.it/150x150" />
</div>
<div class="foreground">
<img src="http://placehold.it/100x100" />
</div>
<div class="foreground">
<img src="http://placehold.it/100x100" />
</div>
</div>
$(document).ready(function () {
$('.container>div').each(function () {
var iniPos = parseInt($(this).css('top'));
var bgspeed = 0.5; //background speed
var fgspeed = 0.8; //foreground speed
var speed;
if ($(this).attr('class') == 'foreground') speed = fgspeed;
else speed = bgspeed;
$(window).scroll(function parallax(iniPos, speed) {
var top = $(window).scrollTop();
var pos = iniPos + speed * top;
$(this).css('top', pos + 'px');
});
});
});
(Fiddle)
但所有 div 都以与页面其余部分相同的速度滚动,我无法找出为什么没有设置新的顶部位置。
【问题讨论】:
标签: javascript jquery