Use html+css+js to realize the small function of returning to the top

The tutorial in this chapter is mainly to implement a relatively common small function in a website. This function is to return to the top.

Function description: When the scroll bar on the right side of the browser slides to a certain position, the icon back to the top is displayed. After returning to the top, the icon is hidden. This article directly gives the specific implementation code for reference only. Detour.

 

Table of contents

1. HTML code

2. CSS code

3. JS code

4. Effect display


1. HTML code

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

2. CSS code


#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;
}

3. JS code

        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' });
        });

4. Effect display

Guess you like

Origin blog.csdn.net/qq_19309473/article/details/132918655