2015-08-15 23 views
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的一切只是用相同的速度頁面的其餘部分滾動,我無法找出爲什麼新的頂端位置沒有被設置。

回答

2

兩個原因:

  1. 裏面你parallaxthiswindow,所以$(this).css()是沒有意義的。
    您需要定義另一個變量的parallax功能外,該.each()裏面,像

    var that = this; 
    

    然後用$(that)parallax

  2. 通過定義iniPosspeed作爲函數的參數:

    function parallax(iniPos, speed) 
    

    你打破這些值。 iniPos將保持滾動值Eventspeed將是未定義的。
    就省略這兩個參數,如

    function parallax() 
    

    (可以省略函數名以及,順便說一句。)

更新JS代碼:

$(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 = $(this).attr('class') == 'foreground' ? fgspeed : bgspeed; 
     var that = this; 
     $(window).scroll(function() { 
      var top = $(window).scrollTop(); 
      var pos = iniPos + speed * top; 
      $(that).css('top', pos + 'px'); 
     }); 
    }); 
}); 

[Updated fiddle ]

+0

Additional我的知識存在問題:所以沒有辦法爲這些函數傳遞參數? – RBk

+1

有(看看['.scroll'](https://api.jquery.com/scroll/)的第二個簽名),但只能用'event.data'。你可以使用'$(window).scroll({iniPos:iniPos,speed:speed},function(event){/ *使用event.data.iniPos和event.data.speed * /})',但我傾向於喜歡關閉。 – Siguza