gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:54:46 25 4
gpt4 key购买 nike

我希望根据滚动缩小 Logo

到目前为止,我有这样的东西

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();

我已经很接近了,但是图像要么开始太宽,要么缩小得太快,我需要它发生在滚动的前 650 像素,如你所见 - 有什么想法吗?也许百分比宽度会更好?

最佳答案

我已经根据您心中有目标大小的假设重写了您的代码,例如滚动 650 像素后,您希望图像宽度为 250 像素。

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

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();

参见http://jsfiddle.net/raad/woun56vk/一个工作示例。

关于javascript - 如何根据滚动位置缩小图像宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27907050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com