我的视差滚动功能有什么错误?

时间:2015-08-15 11:00:20

标签: javascript jquery

我试图让一些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只是以与页面其余部分相同的速度滚动,而且我无法找出为什么新的顶部位置没有被设置。

1 个答案:

答案 0 :(得分:2)

有两个原因:

  1. parallax内,this引用window,因此$(this).css()毫无意义。
    您需要在parallax函数内定义另一个变量,在.each()内,如

    var that = this;
    

    然后在$(that)内使用parallax

  2. iniPosspeed定义为函数参数:

    function parallax(iniPos, speed)
    

    你打破了这些价值观。 iniPos将保留滚动Event的值,speed将不确定。
    只需省略两个参数,例如

    function parallax()
    

    (您也可以省略功能名称,顺便说一句。)

  3. 更新了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]