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

Cal*_*lam 2 javascript jquery

我想缩小基于滚动的徽标

到目前为止,我有这样的事情

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();
Run Code Online (Sandbox Code Playgroud)

我接近了,但是图像开始太宽或收缩太快,如您所见,我需要在滚动的前650像素处进行-有什么想法吗?也许百分比宽度会更好?

Raa*_*aad 5

我已经基于您考虑到目标大小的假设重新编写了代码,例如,在滚动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();
Run Code Online (Sandbox Code Playgroud)

有关工作示例,请参见http://jsfiddle.net/raad/woun56vk/