在jQuery中使用两个ScrollTop()函数?

时间:2017-08-29 11:00:40

标签: javascript jquery

我正在建立一个单页网站,它使用平滑滚动来锚定导航。我也试图添加一个'回到顶部'按钮,但似乎无法使动画工作(点击按钮不做任何事情)。我相信这是因为我使用了两个scrollTop函数。这是正确的,我该如何解决这个问题?

    // Smooth scrolling for page anchors
$(document).ready(function () {
    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').animate({
            'scrollTop': $target.offset().top
        }, 1000, 'swing');
    });

});
// Sticky back to top button
$(document).ready(function () {
    $(window).scroll(function () {
        if ($(this).scrollTop() > 600) {
            $('.go-top').fadeIn("500");
        } else {
            $('.go-top').fadeOut("500");
        }
    });
    $('.go-top').click(function () {
        $('html, body').animate({
            scrollTop: 0
        }, 800);
        return false;
    });
});

1 个答案:

答案 0 :(得分:0)

找到解决方案 - 我不得不删除第二行$(document).ready(function () {代码。