js-返回顶部

 
  <!-- 返回顶部按钮 -->
     <a href="javascript:;" class="backtotop" id="backtotop">
        返回<br>顶部
    </a>

    (function(){
            var backtotop = document.getElementById('backtotop')
            var timer
            backtotop.onclick = function(){
                clearInterval(timer)
                timer = setInterval(function(){
                    document.documentElement.scrollTop -= 100
                    if( document.documentElement.scrollTop <= 0 ){
                        clearInterval(timer)
                    }
                },20)
            }


            // 监听页面的滚动
            window.onscroll = function(){
                // 卷动值
                var scrollTop = document.documentElement.scrollTop || window.scrollY

                if(scrollTop == 0 ){
                    backtotop.style.display = 'none'
                }else{
                    backtotop.style.display = 'block'
                }
            }

        })()
 

.backtotop {
    position: fixed;
    bottom: 80px;
    right: 80px;
    width: 80px;
    height: 80px;
    background: #ccc;
    font-size: 20px;
    text-align: center;
    padding-top: 12px;
    box-sizing: border-box;
    color: #000;
    /* 隐藏元素 */
    display: none;
}
posted @ 2021-12-19 14:15  13522679763-任国强  阅读(55)  评论(0)    收藏  举报