背景中心视差效应跃升至顶部

时间:2016-01-28 12:52:24

标签: jquery background-image parallax

我使用以下代码为背景图像提供简单的视差效果。理想情况下,在CSS中我希望图像居中(不是顶部)。但是,一旦我开始滚动脚本,它就会跳到顶部并开始效果。如果可以改变jquery,那么我无法解决这个问题,所以它从一个居中的图像开始?有人可以帮忙吗?

<div id="para" style="background-image: url('blah')" data-speed="8" data-type="background">
</div>

#para {
    height:500px;
    float:left;
    width:100%;
    background-size:100%;
    background-position: center center;
    background-repeat: no-repeat;
    background-attachemnt: fixed; 
}

//Parallax
$(document).ready(function() {
    if ($(window).width() > 1025) {
        // Cache the Window object
        $window = $(window);
        $('div[data-type="background"]').each(function() {
            var $bgobj = $(this);
            $(window).scroll(function() {
                var yPos = -($window.scrollTop() / $bgobj.data('speed'));
                var coords = '50% ' + yPos + 'px';
                $bgobj.css({
                    backgroundPosition: coords
                });
            });
        });
    }
});

1 个答案:

答案 0 :(得分:1)

您无法为背景位置提供百分比和像素。它应该是一个或另一个。使用百分比单位,然后将$ window.scrollTop()转换为百分比。所以将它乘以100然后除以$ window.height()。

//Parallax
$(document).ready(function() {

    if ($(window).width() > 1025) {
        // Cache the Window object
        $window = $(window);
        $('div[data-type="background"]').each(function() {
            var $bgobj = $(this);
            $(window).scroll(function() {
                var yPos = 50 - ($window.scrollTop() * 100 / $window.height() / $bgobj.data('speed'));
                var coords = '50% ' + yPos + "%";
                $bgobj.css({
                    backgroundPosition: coords
                });
            });
        });
    }
});

您的数据速度属性也需要降低。我发现0.5运作良好。

<div id="para" style="background-image: url('blah')" data-speed="0.5" data-type="background">

相关问题