繁体   English   中英

使用 css 和 js 使背景渐变(径向)在滚动上移动

[英]Make the background gradient(radial) move on scroll using css and js

所以我一直在寻找一种微妙的径向渐变背景效果,当页面滚动时,它会从左向右移动,就像这个网站 - https://hellonesh.io/ 因此,当我检查该站点的代码时,我发现了该效果的相关 HTML 和 CSS -

HTML

<body>
<main>

  <div class="bg" style="background-image: radial-gradient(88.33% 60.62% at 100.87% 48.33%, rgb(86, 53, 173) 0%, rgb(20, 9, 78) 100%);"></div>

  <section id="sec-1">
    ...
  </section>
  <section id="sec-2">
    ...
  </section>
  <section id="sec-3">
    ...
  </section>

</main>

<script>

  //  Need help here

</script>
</body>

CSS

.bg {
    position: fixed;
    display: block;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
}

section {
    height: 100vh;
}

jQuery/js

$(window).on('scroll', function () {
    //When a new section(100Vh) comes into view move the radial gradient left to right or right to left
    // completely lost here
    // $('.bg').css({background-image: "radial-gradient()"});
});

但是我不知道如何在滚动时使径向渐变在视口中移动。 如果是插件请告诉我名字。 如果没有,那么我如何使用 JavaScript 或 jQuery 实现这种效果? 谢谢!

这个问题有两个部分:如何感知另一部分何时进入视野以及何时移动如何根据当前显示的部分移动背景图像。

首先,我们可以使用 InterSectionObserver。 如果我们将观察者附加到每个部分,当该部分进入(或离开,但我们对此不感兴趣)视口时,它就会被触发。

对于第二个,此代码段使用一个 CSS 变量 --x 来说明背景图像径向渐变的“at”x 坐标设置位置。 我不知道您想要每个部分的值,因此此代码段仅查看视图中的部分的 id 并计算仅用于演示的偏移量。

 function callback(entries) { entries.forEach( entry => { if (entry.isIntersecting) { let x = 50 * Number(entry.target.id.replace('sec-', '') - 1); //change to whatever you want the x to be for sec-n bg.style.setProperty('--x', x + '%'); } }); } const bg = document.querySelector('.bg'); const sections = document.querySelectorAll('section'); const observer = new IntersectionObserver(callback); sections.forEach( section => { observer.observe(section); });
 .bg { --x: 0; --y: 48.33%; position: fixed; display: block; top: 0; left: 0; width: 100vw; height: 100vh; background-image: radial-gradient(88.33% 60.62% at var(--x) var(--y), rgb(86, 53, 173) 0%, rgb(20, 9, 78) 100%); } section { height: 100vh; }
 <main> <div class="bg"></div> <section id="sec-1"> ... </section> <section id="sec-2"> ... </section> <section id="sec-3"> ... </section> </main>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM