jquery - 回到顶部

时间:2013-01-10 02:38:34

标签: jquery

我看到这个小提琴样本here

我希望当“到顶部”出现时,点击一下!应平滑或缓慢滚动到顶部

$(window).scroll(function() {
    if ($(this).scrollTop()) {
        $('#toTop').fadeIn();
    } else {
        $('#toTop').fadeOut();
    }
});

5 个答案:

答案 0 :(得分:40)

$("#toTop").click(function () {
   //1 second of animation time
   //html works for FFX but not Chrome
   //body works for Chrome but not FFX
   //This strange selector seems to work universally
   $("html, body").animate({scrollTop: 0}, 1000);
});

http://jsfiddle.net/fjXSq/161/

答案 1 :(得分:10)

Updated JSFiddle with solution

$(window).scroll(function() {
    if ($(this).scrollTop()) {
        $('#toTop').fadeIn();
    } else {
        $('#toTop').fadeOut();
    }
});

$("#toTop").click(function() {
    $("html, body").animate({scrollTop: 0}, 1000);
 });

答案 2 :(得分:4)

首先让我们创建按钮。

<a href="#" class="scrollToTop">Scroll To Top</a>

现在我们可以使用以下CSS设置按钮样式。

<style>
.scrollToTop{
    width:100px; 
    height:130px;
    padding:10px; 
    text-align:center; 
    background: whiteSmoke;
    font-weight: bold;
    color: #444;
    text-decoration: none;
    position:fixed;
    top:75px;
    right:40px;
    display:none;
    background: url('arrow_up.png') no-repeat 0px 20px;
}
.scrollToTop:hover{
    text-decoration:none;
}
</style>

将以下内容复制并粘贴到Javascript文件中以添加Javascript功能。

<script>
$(document).ready(function(){

    //Check to see if the window is top if not then display button
    $(window).scroll(function(){
        if ($(this).scrollTop() > 100) {
            $('.scrollToTop').fadeIn();
        } else {
            $('.scrollToTop').fadeOut();
        }
    });

    //Click event to scroll to top
    $('.scrollToTop').click(function(){
        $('html, body').animate({scrollTop : 0},800);
        return false;
    });

});
</script>

答案 3 :(得分:0)

$(document).ready(function(){ 
   $(window).scroll(function(){ 
       if ($(this).scrollTop() > 100) { 
           $('#toTop').fadeIn(); 
       } else { 
           $('#toTop').fadeOut(); 
       } 
   }); 
   $('#toTop').click(function(){ 
       $("html, body").animate({ scrollTop: 0 }, 600); 
       return false; 
   }); 
});

现场演示,完整的脚本和教程可以在这里查看 - Back to top button using jQuery and CSS

答案 4 :(得分:0)

See JS Fiddle

       $(window).on("scroll",function() {
        if ($(this).scrollTop() > 50 ) {
            $('#toTop').fadeIn(400);
        } else {
            $('#toTop').fadeOut(400);
        }
    });

    $("#toTop").on("click",function() {
        $("html, body").animate({scrollTop: 0}, 1200);
     });