0
我試圖讓一些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的一切只是用相同的速度頁面的其餘部分滾動,我無法找出爲什麼新的頂端位置沒有被設置。
Additional我的知識存在問題:所以沒有辦法爲這些函數傳遞參數? – RBk
有(看看['.scroll'](https://api.jquery.com/scroll/)的第二個簽名),但只能用'event.data'。你可以使用'$(window).scroll({iniPos:iniPos,speed:speed},function(event){/ *使用event.data.iniPos和event.data.speed * /})',但我傾向於喜歡關閉。 – Siguza