如何在无限滚动上创建渐变背景?

问题描述 投票:-1回答:1

我正在尝试创建一个无限滚动页面,其中背景是根据滚动位置而变化的渐变。

我发现了可以与时间和日期配合使用的无限滚动代码。我想将其替换为渐变任务。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>

<body>

<h1>Scroll me</h1>

<script>
  function populate() {
    while(true) {
      let windowRelativeBottom = document.documentElement.getBoundingClientRect().bottom;
      if (windowRelativeBottom > document.documentElement.clientHeight + 100) break;
      document.body.insertAdjacentHTML("beforeend", `<p>Date: ${new Date()}</p>`);
    }
  }

  window.addEventListener('scroll', populate);

  populate(); // init document
</script>

</body>
</html>
javascript html css gradient infinite-scroll
1个回答
0
投票

真的很简单,无需复杂化。如果将渐变视为背景图像,则可以这样重复。背景可以“无限重复”,因此,我们可以将背景的垂直高度设置为我们知道会重复的高度。即定义了渐变后,使用background-size

background-size: 100% 400vh;
background-repeat: repeat-y; /* this is set to repeat by default, but putting this in helps drive the point home */

我们的渐变将每4个视口高度重复,并且由于您的JS,文档会随着高度的增加而不断增加,因此我们看到它无限地重复。只需确保渐变以与开始时相同的颜色结束,否则您会看到一个切口。

如果您不想看一些闪烁的颜色,请不要打开此代码笔:https://codepen.io/joshdavenport/pen/rNNOJWM

© www.soinside.com 2019 - 2024. All rights reserved.