繁体   English   中英

背景中心视差效果跳到顶部

[英]Background center parallax effect jumps to top

我正在使用以下代码为背景图像提供简单的视差效果。 理想情况下,在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
                });
            });
        });
    }
});

您不能给背景位置一个百分比和像素。 应该是其中之一。 使用百分比单位,然后将$ 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">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM