本文介绍: react实现滚动到顶部组件

新建ScrollToTop.js

import React, { useState, useEffect } from 'react';
import './ScrollToTop.css';

function ScrollToTop() {
    const [isVisible, setIsVisible] = useState(true);

    // Show button when page is scorlled upto given distance
    const toggleVisibility = () => {
        console.log(1)
        console.log(window.scrollY)
        if (window.scrollY > 300) {
            setIsVisible(true);
        } else {
            setIsVisible(false);
        }
    };

    // Set the top cordinate to 0
    // make scrolling smooth
    const scrollToTop = () => {
        window.scrollTo({
            top: 0,
            behavior: "smooth"
        });
    };

    useEffect(() => {
        window.addEventListener("scroll", toggleVisibility);
        return () => window.removeEventListener("scroll", toggleVisibility);
    }, []);

    return ( isVisible &&
        <div  className="scroll-to-top" onClick={scrollToTop}>
            {isVisible &&
                <div onClick={scrollToTop}>
                    <i className="icon fas fa-chevron-up">1</i>
                </div>}
        </div>
    );
}

export default ScrollToTop;

css

.scroll-to-top {
    position: fixed;
    bottom: 20px;
    right: 20px;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 50px;
    width: 50px;
    background-color: #007BFF;
    color: white;
    border-radius: 50%;
    transition: visibility 0s, opacity 0.5s linear;
}

.scroll-to-top:hover {
    background-color: #0056b3;
}

.icon {
    font-size: 24px;
}

.scroll-to-top.show {
    visibility: visible;
}

 使用

原文地址:https://blog.csdn.net/weixin_51526447/article/details/135840506

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_62439.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注