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



这是我的代码在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,而页面向下滚动,背景必须保持在固定位置。

它工作:我的意思是,当我滚动一点背景放大,好吧!,然后开始向下滚动……我不明白为什么,我到处找,试图找到一个解释。

在您的scroll方法中,您使用以下行来处理背景:

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

It 变换背景,即缩放它。注释掉或使用其他转换来查看差异。如果你不需要它,把这条线全部去掉。

__UPDATE__

看一下这把小提琴。我修改了图片的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(缩放),如果我继续滚动,它又开始放大。

最新更新