jQuery返回顶部代码

页面较长时,使用返回顶部按钮比较方便,在电商中必备操作。下面自己制作一个js文件,totop.js,把它直接引用到需要的网页中即可。

$(function () {
    $("body").append($("<div id='totop'></div>"));
    $("#totop").hide();
    $(window).scroll(function () {
        if ($(window).scrollTop() > 100) {
            $("#totop").fadeIn(500);
        }
        else {
            $("#totop").fadeOut(500);
        }
    });
    $("#totop").click(function () {
        $('body,html').animate({ scrollTop: 0 }, 100);
        return false;
    });
    window.onload = function () {
        $(window).scroll();
    };
});

 css:

/*回到顶部*/
#totop{
    background:url(/themes/default/images/top_bg.png) no-repeat left top;
    width:40px ;height:40px;
    position:fixed;
    left:50%;bottom:20%;
    margin-left:605px;
}
#totop:hover{
    background:url(/themes/default/images/top_bg.png) no-repeat left -40px;
    cursor:pointer
}

 

posted @ 2016-04-18 12:47  lunawzh  阅读(717)  评论(0编辑  收藏  举报