回到顶部按钮

本实战来自个人研究,不一定是最好的!

仅支持IE8及以上版本!

HTML:

1 <!--回到顶部 开始-->
2     <div id="to_top" class="to_top">
3         <i class="to_top_pic"></i>
4     </div>
5 <!--回到顶部 结束-->

CSS:

1 /*回到顶部按钮,切忌初始化不要用float、position(absolute,relative,fixed)等脱离文档的定位*/
2 #to_top {
3     width: 50px;
4     height: 50px;
5     margin: 500px 0 0 1020px;
6     background: #efefef;
7     /*position: fixed;*/
8     /*top: 0;*/
9 }

JS:

/**
     * 回到顶部
     * */
    var toTopDistance = 700;

    //侦听滚动事件
    $(window).on('scroll', function () {
        //console.log($(document).scrollTop());
        //console.log(toTopDistance);

        /**
         * 滚到一定程度,回到顶部按钮一直显示在右上方*/
        if($(document).scrollTop() >= toTopDistance) {

            $('#to_top').css({
                'position': 'fixed',
                'top': 0,
                'margin': '0 0 0 1020px'
            });

        }else {
            $('#to_top').css({
                'position': 'static',
                'margin': '500px 0 0 1020px'
            });
        }
    });
原文地址:https://www.cnblogs.com/lqcdsns/p/5514976.html