如何在滚动时放大背景图像?

How zoom the background-image in while scrolling?

这是我在 html、css 和 js 中的代码(非常简化):

<body>
    <div id="wrapper">
        <section id="first">
            <div class="background"></div>
            <div class="videoBackground"></div>
            <div class="content">
                <div id="titleGFS" class="title">Ipse eorum</div>
                <div id="txt1" class="text">Ipse eorum opinionibus accedo, qui Germaniae...</div>
                <div id="txt2" class="text">Personalmente inclino verso l'opinione di quanti ritengono che i popoli della Germania...</div>
            </div>
        </section>

        <!-- other sections -->

    </div>
</body>

CSS:

    html,body{
        width: 100%;
        height: 100%;

        margin: 0;
        padding: 0;
    } 

    #wrapper{
        min-width: 1000px;
    }

    section{
        min-height: 100vh;
    }

    #first{
        color: whitesmoke;
        background: url('1.jpg') no-repeat center;
        background-size: cover;   
    }

    #first .background{
        background-image: none;
        background-attachment: fixed;
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;
        height: 100vh;
        width: 100vw;
        position: absolute;
        top: 0;
        left: 0;
        z-index: -1;
    }

JS:

/*Change background (I need it in this way)*/
$('#first').css({background:'none'});
$('#first .background').css({backgroundImage: "url('1.jpg')"});

/*Scrolling*/
$(window).scroll(function(){
    var $maxScroll=300;
    var $maxScale=1.3;
    var $x=$(window).scrollTop()/1000+1;
    if($(window).scrollTop()>$maxScroll) $x=$maxScale;
    $('#first .background').css({transform: 'scale('+$x+','+$x+')'});

我想做的事情:在页面向下滚动的同时放大背景图片,缩放比例限制为1.3,背景必须保持在固定位置。

它有效:我的意思是,当我滚动一点背景放大时,好吧!,然后它开始向下滚动......我不明白为什么,我试图通过到处搜索找到解释。

在你的滚动方法中,你用这条线来玩背景:

 $('#first .background').css({transform: 'scale('+$x+','+$x+')'});

变换 背景,即缩放它。注释掉或尝试其他转换以查看差异。如果您不需要它,请完全删除该行。

__UPDATE__

看看this fiddle。我将图像 URL 更改如下:

$('#first').css({background:'none'});

/*Scrolling*/
$(window).scroll(function(){
    var $maxScroll=500;
    var $maxScale=1.3;
    var $x=$(window).scrollTop()/100+1;
    console.log("scrollTop : " + $(window).scrollTop() + "- x : " + $x);
    if($(window).scrollTop()>$maxScroll) $x=$maxScale;
//    $('#first .background').css({transform: 'scale('+$x+','+$x+')'});

        $('#first .background').css({transform: 'scale('+$x+','+$x+')'});

});

我还在下面的行中将 1000 更改为 100:

var $x=$(window).scrollTop()/100+1;

通过这种方式,我使除法 ($x) 的值更大,并且有助于缩放更加明显。

让我试着解释一下在您的情况下发生了什么:缩放比例非常小,以至于您很快就遇到了障碍,缩放比例停止了。

不过,就我而言,请注意控制台,缩放范围更大,因此我会越来越多地缩放图像。但是在我超过 500 限制后,由于以下行图像被缩小:

if($(window).scrollTop()>$maxScroll) $x=$maxScale;

其中 $x 重置为 $maxScale(缩小),如果我继续滚动,它会再次开始放大。

现在有意义吗?