javascript滚动滞后 - Chrome

时间:2012-11-19 22:01:50

标签: jquery google-chrome scroll lag parallax

我正试图改变背景 - 假设和用户滚动时的top属性。我想为精灵模拟背景和视差的固定位置,所以我做了以下几点:

HTML部分

<section id="first" data-type="background" data-speed="1">
    <div id="sprite1" data-type="sprite" data-speed="-1.5"></div>
    <div id="sprite2" data-type="sprite" data-speed="-1"></div>
</section>
<section id="second" data-type="background" data-speed="1">

</section>

CSS部分

section {
    width: 100%;
    height: 1000px;
    position: relative;
}

#first {
   background: url('../img/bg1.png'), no-repeat, fixed, 50% 0;
}

#second {
    background: url('../img/bg2.png'), no-repeat, fixed, 50% 0;
}

#sprite1 {
    position: relative;
    background: url('../img/sprite1.png'), no-repeat, fixed, 50% 0;
    width: 100px;
    height: 100px;
    top: 550px;
    left: 100px;
}

#sprite2 {
    position: relative;
    background: url('../img/sprite2.png'), no-repeat, fixed, 50% 0;
    width: 200px;
    height: 200px;
    top: 650px;
    left: 150px;
}

JS部分

$(document).ready(function() {

    /* Initialisation */
    var $window = $(window);

    var offset = 0;
    $('section[data-type="background"]').each(function(index) {
        var $this = $(this);
        console.log($this);
        $this.data('data', {
            height: $this.height() + offset,
            speed: parseFloat($this.attr('data-speed'))
        });
        offset = $this.data('data').height;
    });

    $('div[data-type="sprite"]').each(function(index) {
        var $this = $(this);
        $this.data('data', {
                xPosition: parseInt($this.css('top').replace(/px/, '')),
            yPosition: parseInt($this.css('left').replace(/px/, '')),
            speed: parseFloat($this.attr('data-speed'))
        });
        console.log($this.data('data'));
    });

    $('#first').data('position', '0');
    $(window).scroll(function(){
        console.log($(this));
        var scrollPos = parseInt($window.scrollTop());
        $('section[data-type="background"]').each(function(index) {
            var $this = $(this);
            $this.css('background-position', '50% ' + (scrollPos / $this.data('speed') + $this.data('data').height) + 'px');
        });
        $('div[data-type="sprite"]').each(function(index) {
            var $this = $(this);
            $this.css('top', ((scrollPos / $this.data('data').speed) + $this.data('data').xPosition) + 'px');
        });
    });

});

您可以看到结果here

在Firefox上没有问题,背景似乎已修复,但在Chrome上,似乎浏览器通过滚动页面并在执行代码后启动。所以它在Chrome上完全被猛烈抨击...... 有没有办法在页面滚动之前强制执行代码?

Thx:)

1 个答案:

答案 0 :(得分:0)

我不确定你在滚动动画中提到的是什么,我猜。您可以开始使用$ .animate()来使转换更平滑,而不是使用$ .css()。我也在IE中检查了它,它似乎也做了同样的事情。当使用$ .animate()而不是$ .css时,可能会在多个浏览器中以不同方式注册的$ .scroll()可能会被平滑掉。

相关问题