【发布时间】:2020-10-21 22:13:24
【问题描述】:
以这个网站为例 (https://hostmarked.dk/),我可以看到下面的第二张图片在一个元素内,其中还有 3 个可伸缩元素。
当您滚动页面时,3 个白色元素的尺寸会减小,直到整个图像可见,然后效果停止。
我不确定如何将此缩放操作链接到 jquery 中的滚动。
【问题讨论】:
以这个网站为例 (https://hostmarked.dk/),我可以看到下面的第二张图片在一个元素内,其中还有 3 个可伸缩元素。
当您滚动页面时,3 个白色元素的尺寸会减小,直到整个图像可见,然后效果停止。
我不确定如何将此缩放操作链接到 jquery 中的滚动。
【问题讨论】:
这是一个例子:
$(document).scroll((e) => {
// How much the user has scrolled
let percentScrolled = window.scrollY / window.innerHeight;
let minWidth = 100;
let maxWidth = 200;
// How wide the image should be
let width = percentScrolled * (maxWidth - minWidth) + minWidth;
let minHeight = 100;
let maxHeight = 200;
// How tall the image should be
let height = percentScrolled * (maxHeight - minHeight) + minHeight;
// The starting position
let originalPosition = [100, 100];
// Update width and height
$(".fake-image").css("width", width + "px");
$(".fake-image").css("height", height + "px");
// Move the image so the center stays the same
$(".fake-image").css("left", originalPosition[0] - (width - minWidth) / 2 + "px");
$(".fake-image").css("top", originalPosition[1] - (height - minHeight) / 2 + "px");
});
body {
/* This just makes sure the whole page is scrollable */
height: 200vh;
width: 100vh;
}
.fake-image {
background-color: black;
width: 100px;
height: 100px;
margin: auto;
position: fixed;
left: 100px;
top: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fake-image"></div>
当窗口滚动时,这会调整图像的大小和位置。更多信息请参见代码中的 cmets。
【讨论】: