【问题标题】:What is the error in my function for parallax scrolling?我的视差滚动功能有什么错误?
【发布时间】: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


    【解决方案1】:

    两个原因:

    1. 在你的parallax里面,this指的是window,所以$(this).css()是没有意义的。
      您需要在parallax 函数之外定义另一个变量,在.each() 内部,例如

      var that = this;
      

      然后在parallax 中使用$(that)

    2. 通过将iniPosspeed 定义为函数参数:

      function parallax(iniPos, speed)
      

      你打破了这些价值观。 iniPos 将保存滚动的值 Event,而 speed 将是未定义的。
      只需省略两个参数,如

      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]

    【讨论】:

    • 据我所知还有一个问题:所以没有办法为这些函数传递参数?
    • 有(看看.scroll 的第二个签名),但只是event.data。你可以使用$(window).scroll({ iniPos: iniPos, speed: speed }, function(event) { /* work with event.data.iniPos and event.data.speed */ }),但我更喜欢闭包。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多