[英]How to shrink an image width based on scroll position
我希望根据滚动缩小徽标
到目前为止,我有这样的事情
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/ 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.