滚动缩放比例

时间:2020-10-21 13:38:44

标签: jquery css animation

以该网站为例(https://hostmarked.dk/),我可以看到第二个图像位于一个元素内部,其中还包含3个可扩展元素。

滚动页面时,这3个白色元素会减小尺寸,直到整个图像可见为止,然后效果停止。

我不确定如何将此缩放操作链接到jquery中的滚动。

1 个答案:

答案 0 :(得分:1)

这是一个例子:

$(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>

滚动窗口时,它将调整图像大小并重新放置图像。有关更多信息,请参见代码中的注释。