美文网首页
派蒙 点击回顶部 Next.js

派蒙 点击回顶部 Next.js

作者: 薛定谔的程序 | 来源:发表于2021-07-15 19:07 被阅读0次
    paimon.gif
    import { FC, ReactElement, useCallback, useEffect, useState } from "react";
    import Image from "next/image";
    import Paimon from "../../assets/paimon_small.png";
    import styled from "styled-components";
    
    interface IProps {}
    
    const ScrollToTop: FC<IProps> = (): ReactElement => {
      const [state, setState] = useState(0);
    
      const listenScroll = useCallback(() => {
        if (window?.scrollY > 100 && window?.scrollY < 400) {
          state !== 1 && setState(1);
        } else if (window?.scrollY > 400) {
          state !== 2 && setState(2);
        } else {
          state && setState(0);
        }
      }, [state]);
    
      useEffect(() => {
        window.addEventListener("scroll", listenScroll);
        return () => {
          window.removeEventListener("scroll", listenScroll);
        };
      }, [listenScroll, state]);
    
      const scrollToTop = useCallback(() => {
        const sTop = document.documentElement.scrollTop || document.body.scrollTop;
        if (sTop > 0) {
          window.requestAnimationFrame(scrollToTop);
          window.scrollTo(0, sTop - sTop / 8);
        }
      }, []);
    
      return (
        <Container show={state} onClick={scrollToTop}>
          <Image width="100" height="200" src={Paimon} alt="paimon" />
        </Container>
      );
    };
    
    export default ScrollToTop;
    
    const Container = styled.div<{ show?: number }>`
      position: fixed;
      bottom: 100px;
      transition-property: opacity, right, transform;
      transition-duration: 0.5s;
      transform-origin: center;
      transition-timing-function: ease-out;
      right: ${({ show }) => (show ? (show == 1 ? "-70px" : "0") : "-100px")};
      ${({ show }) => (show == 1 ? "transform: rotate(-40deg);" : undefined)}
      opacity: ${props => (props.show ? 1 : 0)};
      z-index: ${props => props.theme.index.fixed};
      cursor: pointer;
    
      &:hover {
        right: 0;
        transform: rotate(0);
      }
    `;
    
    

    相关文章

      网友评论

          本文标题:派蒙 点击回顶部 Next.js

          本文链接:https://www.haomeiwen.com/subject/gbsmpltx.html