Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/464.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何根据滚动位置缩小图像宽度_Javascript_Jquery - Fatal编程技术网

Javascript 如何根据滚动位置缩小图像宽度

Javascript 如何根据滚动位置缩小图像宽度,javascript,jquery,Javascript,Jquery,我想缩小一个基于卷轴的标志 到目前为止,我有类似的东西 logoSize = function(){ var headerOffset = $(window).height() - 650; var maxScrollDistance = 1300; $(window).scroll(function() { var percentage = maxScrollDistance / $(document).scrollTop(); if (

我想缩小一个基于卷轴的标志

到目前为止,我有类似的东西

logoSize = function(){
    var headerOffset = $(window).height() - 650;
    var maxScrollDistance = 1300;
    $(window).scroll(function() {
        var percentage = maxScrollDistance / $(document).scrollTop();
        if (percentage <= headerOffset) {
            $('.logo').css('width', percentage * 64);
        }
        console.log(percentage);
    });
}

logoSize();
logoSize=function(){
var headerOffset=$(窗口).height()-650;
var maxScrollDistance=1300;
$(窗口)。滚动(函数(){
var percentage=maxScrollDistance/$(document).scrollTop();

如果(百分比我基于您心中有目标大小的假设重新编写了您的代码,例如,在滚动650px后,您希望您的图像宽度为250px

它在本机大小和目标大小之间平滑滚动,并考虑到窗口高度可能小于最大滚动距离的事实:

logoSize = function () {
    // Get the real width of the logo image
    var theLogo = $("#thelogo");
    var newImage = new Image();
    newImage.src = theLogo.attr("src");
    var imgWidth = newImage.width;

    // distance over which zoom effect takes place
    var maxScrollDistance = 650;

    // set to window height if that is smaller
    maxScrollDistance = Math.min(maxScrollDistance, $(window).height());

    // width at maximum zoom out (i.e. when window has scrolled maxScrollDistance)
    var widthAtMax = 500;

    // calculate diff and how many pixels to zoom per pixel scrolled
    var widthDiff = imgWidth - widthAtMax;
    var pixelsPerScroll =(widthDiff / maxScrollDistance);

    $(window).scroll(function () {
        // the currently scrolled-to position - max-out at maxScrollDistance
        var scrollTopPos = Math.min($(document).scrollTop(), maxScrollDistance);

        // how many pixels to adjust by
        var scrollChangePx =  Math.floor(scrollTopPos * pixelsPerScroll);

        // calculate the new width
        var zoomedWidth = imgWidth - scrollChangePx;

        // set the width
        $('.logo').css('width', zoomedWidth);
    });
}

logoSize();

有关工作示例,请参阅。

如果发生得太快,请按更改的宽度设置动画…而不仅仅是更改它。