返回顶部

“返回顶部”按钮的实现

字号+ 来源:网络收集 编辑整理: 飞燕前端网 2017-03-08 15:31:11

在很多地方,我们都会用到“返回顶部”按钮。那么这个要怎么实现呢?1、html代码返回顶部2、css代码.back_to_top{ position: fixed; bottom:30px; right: 30px; border...

在很多地方,我们都会用到“返回顶部”按钮。那么这个要怎么实现呢?

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()  获取整个文档的高度

1.飞燕前端网遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.飞燕前端网的原创文章,请转载时务必注明文章作者和"来源:飞燕前端网",不尊重原创的行为飞燕前端网或将追究责任。

相关文章
网友点评