【问题标题】:Changing elements (like fixed logo) color, depending on the section in React根据 React 中的部分更改元素(如固定徽标)颜色
【发布时间】:2018-03-24 01:53:49
【问题描述】:

我想达到this one这样的效果 在 React 网页中,但不使用 jQuery。我一直在寻找该库的替代品,但没有结果。我见过很多类似的问题,但每个问题都是用 jQuery 回答的。

效果基本上是在我向下滚动浏览不同部分时更改徽标(以及页面中的其他元素)的颜色。

有谁知道实现这一目标的方法吗?

【问题讨论】:

    标签: javascript reactjs colors


    【解决方案1】:

    可以做到这一点的一种方法是将徽标动态地居中到它们自己的容器中,有点像模拟位置固定,但使用绝对位置,因此每个徽标都包含在它们自己的部分中,而不是像位置固定那样全局。 这样,当您滚动到下一部分时,第二部分会覆盖第一部分,使其看起来像是在过渡。

    我在这里创建了一个概念证明:

    https://codesandbox.io/s/9k4o3zoo

    注意:此演示是概念验证,可以通过使用请求动画帧和限制等功能来提高性能。

    代码:

    class App extends React.Component {
      state = {};
    
      handleScroll = e => {
        if (!this.logo1) return;
        const pageY = e.pageY;
    
        // 600 is the height of each section
        this.setState(prevState => ({
          y: Math.abs(pageY),
          y2: Math.abs(pageY) - 600
        }));
      };
    
      componentDidMount() {
        window.addEventListener("scroll", this.handleScroll);
      }
    
      render() {
        const { y, y2 } = this.state;
        return (
          <div>
            <section className="first">
              <h1
                className="logo"
                style={{ transform: `translateY(${y}px)` }}
                ref={logo => {
                  this.logo1 = logo;
                }}
              >
                YOUR LOGO
              </h1>
            </section>
            <section className="second">
              <h1
                className="logo"
                style={{ transform: `translateY(${y2}px)` }}
                ref={logo => {
                  this.logo2 = logo;
                }}
              >
                YOUR LOGO
              </h1>
            </section>
          </div>
        );
      }
    }
    

    CSS 将是:

    section {
      height: 600px;
      width: 100%;
      position: relative;
      font-family: helvetica, arial;
      font-size: 25px;
      overflow: hidden;
    }
    
    .first {
      background: salmon;
      z-index: 1;
    }
    
    .first .logo {
      color: black;
    }
    
    .second {
      background: royalBlue;
      z-index: 2;
    }
    
    .second .logo {
      color: red;
    }
    
    .logo {
      position: absolute;
      margin: auto;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      width: 230px;
      height: 30px;
    }
    

    【讨论】:

    • 谢谢伊格纳西奥。它在 Firefox 中就像一个魅力,但在 Chrome 或 Safari 上不起作用。我会以您的解决方案为起点尝试不同的事情,然后告诉您我的发现。
    • 你试过使用requestAnimationFrame吗?这是一种以 60fps 制作动画的好方法,如果您可以分享您的代码并看看我们能做些什么,那就太好了
    • 抱歉回复晚了。我没有,但我会试试看。谢谢你的回答。
    猜你喜欢
    • 1970-01-01
    • 2022-09-23
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多