单击时为什么我的返回顶部按钮不会返回顶部?

时间:2014-11-27 17:42:41

标签: jquery scroll scrolltop

  // ===== Scroll to Top ==== 
         $(window).scroll(function() {
             if ($(this).scrollTop() >= 50) { // If page is scrolled more than 50px
                 $('#return-to-top').fadeIn(200); // Fade in the arrow
             } else {
                 $('#return-to-top').fadeOut(200); // Else fade out the arrow
             }
         });
         $('#return-to-top').click(function() { // When arrow is clicked
             $('body,html').animate({
                 scrollTop: 0 // Scroll to top of body
             }, 500);
         });

每当我点击按钮时,它都不会将您带到顶部。它只是没有做任何事情。任何帮助将不胜感激。这是css:http://pastebin.com/1SF4S6Vg

2 个答案:

答案 0 :(得分:0)

您的语法正确,因为我已在此FIDDLE中重新创建。我猜你在功能上错过了.ready()。试试这个:

$(function () {
    $(window).scroll(function () {
        if ($(this).scrollTop() >= 50) { // If page is scrolled more than 50px
            $('#return-to-top').fadeIn(200); // Fade in the arrow
        } else {
            $('#return-to-top').fadeOut(200); // Else fade out the arrow
        }
    });
    $('#return-to-top').click(function () { // When arrow is clicked
        $('body,html').animate({
            scrollTop: 0 // Scroll to top of body
        }, 500);
    });
});

答案 1 :(得分:0)

正如@Tomanow回答的那样,使用$(function () {...}使其有效。如果没有,您在调用此函数时需要额外的#top标记(或其他一些锚点),这也有效,但在您点击后会在链接中显示#top

相关问题