首页 > 解决方案 > 滚动时更改所选按钮和图像

问题描述

在我的 html 中,我有 3 个按钮(将在我的页面上的一个部分中看到),每个按钮都有一个相关的图像。当您从顶部开始时,您将在左侧看到 3 个按钮,在右侧看到所选按钮的图像。它将首先从选择的第一个按钮开始。

这个想法是在向下滚动到某个高度时,我想将活动按钮更改为第二个按钮,并更改右侧的图像。然后当再次继续滚动时,它应该选择第三个按钮及其图像。

我应该使用哪个事件或 css 样式来产生这种行为?我应该使用交叉点观察器吗?

我想使用 Html、css 和 js

<section
  style="display: flex; flex-direction: column; padding-left: 100px; height: auto; position: sticky; top: 0"
>
  <button style="width: 100px; height: 100px; background-color: red">
    Button 1
  </button>
  <button style="width: 100px; height: 100px">Button 2</button>
  <button style="width: 100px; height: 100px">Button 3</button>
  <button style="width: 100px; height: 100px">Button 4</button>
  <button style="width: 100px; height: 100px">Button 5</button>
  <button style="width: 100px; height: 100px">Button 6</button>
  <button style="width: 100px; height: 100px">Button 7</button>
</section>
<section style="height: 200px">Section 2</section>
<section style="height: 200px">Section 3</section>
<section style="height: 200px">Section 4</section>
<section style="height: 200px">Section 5</section>

标签: htmlcss

解决方案


IntersectionObserver 在这里可能很有用。

只设置一个观察者,然后设置观察者。观察(你的每个部分)。

如果某物是相交的,则突出显示其相关按钮并显示其图像。如果 !isIntersecting,移除它的按钮高亮。

查看您可以在 MDN 上设置的选项的详细信息。

特别是,在设置突出显示和图像之前,您必须决定必须看到多少部分,以及如果同时显示多个部分,则哪个部分“获胜”。

如果您需要进一步的帮助,请告诉我,但请在您的问题代码中包含一些部分,以便更轻松地查看所需内容。


推荐阅读