【问题标题】:How to prevent keyframe animation to restart when scrolling again?再次滚动时如何防止关键帧动画重新​​启动?
【发布时间】:2021-03-31 08:18:49
【问题描述】:

我有一个反应页面,其主要部分在视口中的可见性由交叉点观察者观察。一旦用户看到该部分,就会触发一个关键帧(通常是从 0 到 1 的基本不透明度过渡)。

问题是每次我向上/向下滚动时关键帧都会重新开始,这从用户体验的角度来看很烦人。如何防止关键帧动画发生后再次触发?

这是一个代码sn-p:

import { useInView } from "react-intersection-observer";

const reveal = keyframes`
  0% {opacity: 0;}
  100% {opacity: 1;}
`;

const Section = styled.section`
  margin: 64px 0;
`;

const SectionTitle = styled.h3<{ inView: boolean }>`
  opacity: 0;
  animation: ${({ inView }) =>
    inView &&
    css`
      ${reveal} 1s ease forwards
    `};
`;

const Text = styled.p<{ inView: boolean }>`
  opacity: 0;
  animation: ${({ inView }) =>
    inView &&
    css`
      ${reveal} 1.5s ease forwards
    `};
`;


export default function Home() {
  const [about, aboutInView] = useInView();
  const [pricing, pricingInView] = useInView();
  return (
    <div>
      <Header />
        <Section ref={about}>
              <SectionTitle inView={aboutInView}>About</SectionTitle>
              <Text inView={aboutInView}>about text</Text>
        </Section>
        <Section ref={pricing}>
          <Text inView={pricingInView}>pricing text</Text>
        </Section>
    </div>
  );
}

【问题讨论】:

  • 因为useInView()调用来回设置inView,你只需要确保一旦它变成true,就不会再次触发。您可以使用选项更新钩子以仅触发一次,或使用useRef 和useMemo 的组合仅在其为真时更改
  • 谢谢,我没有看到 triggerOnce 选项 ;)!

标签: css reactjs css-animations


【解决方案1】:

在调用 useInView Hook 时设置 {triggerOnce: true}

// Generally 
const [ref, inView, entry] = useInView({ threshold: 0, triggerOnce: true });

// Your Case
const [about, aboutInView] = useInView({ triggerOnce: true });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 2017-05-10
    • 2018-11-07
    • 1970-01-01
    • 2022-12-13
    • 2016-09-29
    • 2016-12-26
    相关资源
    最近更新 更多