利用html+css+js实现回到顶部小功能

本章教程,主要是实现一个网站中比较常见的小功能,这个功能就是回到顶部。

功能描述:当浏览器右侧的滚动条,滑动到某个位置的时候,显示回到顶部图标,回到顶部之后,图标作隐藏处理,本文直接给出具体的实现代码,仅供参考,大佬绕道。

目录

一、HTML代码

二、CSS代码

三 、JS代码

四、效果展示


一、HTML代码

    <a href="#" id="back-to-top" title="Back to Top"><i class="fa fa-angle-up fa-1x"></i></a>

二、CSS代码


#back-to-top {
    display: none;
    position: fixed;
    bottom: 20px;
    right: 20px;
    z-index: 99;
    font-size: 18px;
    color: #fff;
    background-color: #A233C6;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    opacity: 0.7;
    cursor: pointer;
}

#back-to-top:hover {
    opacity: 1;
}

三 、JS代码

        window.addEventListener('scroll', function() {
            var backToTopButton = document.getElementById('back-to-top');
            if (window.pageYOffset > 100) {
                backToTopButton.style.display = 'block';
            } else {
                backToTopButton.style.display = 'none';
            }
        });

        document.getElementById('back-to-top').addEventListener('click', function(e) {
            e.preventDefault();
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });

四、效果展示

猜你喜欢

转载自blog.csdn.net/qq_19309473/article/details/132918655