jQuery实现返回顶部按钮功能

  • html结构
  • <div class="toolbar">
                <a href="javascript:;" class="toolbar-item">
                    <span class="toolbar-btn" id="backtop">
                        <i class="toolbar-icon icon-upload2"></i>  //图标字体
                        <span class="toolbar-text">返回<br />顶部</span>
                    </span>
                </a>
    </div>
  • css样式
  • .toolbar{
        position: fixed;
        right: 10px;
        bottom: 20px;
    }
    .toolbar-item{
        position: relative;
        display: block;
        width: 50px;
        height: 50px;
    
    
        &:hover{
            .toolbar-icon{
                top: -@toolbar-size;
            }
            .toolbar-text {
                top: 0;
            }
        }
    }
    .toolbar-btn{
        position: absolute;
        left: 0;
        top: 0;
        width: 50px;
        height: 50px;
        overflow: hidden;
    
        .toolbar-icon{
            position: absolute;
            left: 0;
            top: 0;
            width: 50px;
            height: 50px;
            background-color: #ccc;
            font-size: 30px;
            color: #fff;
            text-align: center;
            transition: top 1s;
        } 
        .toolbar-text{
            position: absolute;
            left: 0;
            top: 50px;
            width: 50px;
            height:50px;
            background-color: #A0A0A0;
            font-size: 14px;
            color: #fff;
            text-align: center;
            transition: top 1s;
        }
    }
  • jQuery实现返回顶部
  • <script type="text/javascript">
            $(function() {
                $('#backtop').on('click',move);   //绑定点击事件,也可写成:$("#backtop").click(function(){  //代码   })
                $(window).on('scroll',function(){
                    checkposition( $(window).height() );
                });
    
                function move() {
                    $('html,body').animate({
                        scrollTop: 0
                    },800);
                }
    
                function checkposition(H) {
                    if($(window).scrollTop() > H){
                        $('#backtop').fadeIn();
                    }
                    else{
                        $('#backtop').fadeOut();
                    }
                }
            })
    </script>

     

至此,返回顶部按钮功能基本实现

posted @ 2016-05-21 11:18  zhuyinxiaozi  阅读(707)  评论(0编辑  收藏  举报