返回顶部

1.html代码

<button class="back_to_top">返回顶部</button>

2.css代码

.back_to_top{
    position: fixed;
    bottom:30px;
    right: 30px;
    border:1px solid #888;
}

3.js代码

    var backButton=$('.back_to_top');
    function backToTop() {
        $('html,body').animate({
            scrollTop: 0
        }, 800);
    }
    backButton.on('click', backToTop);
 
    $(window).on('scroll', function () {/*当滚动条的垂直位置大于浏览器所能看到的页面的那部分的高度时,回到顶部按钮就显示 */
        if ($(window).scrollTop() > $(window).height())
            backButton.fadeIn();
        else
            backButton.fadeOut();
    });
    $(window).trigger('scroll');/*触发滚动事件,避免刷新的时候显示回到顶部按钮*/

获取滚动条的垂直偏移,即当前页面顶端到整个页面顶端的距离

$(window).scrollTop() 或者$(document).scrollTop() ,但是前者更兼容
$(window).height() 获取当前浏览器窗口的大小,浏览器拉伸大小就会变

$(document).height() 获取整个文档的高度

posted @ 2021-12-27 14:17  南北t  阅读(186)  评论(0)    收藏  举报