scroll()和scrollTop()不起作用

时间:2014-06-16 10:47:45

标签: jquery scroll scrolltop

我想通过jquery创建一个'go-to-top'按钮 - 但是scroll()和scrollTop()不起作用......

这是我的设置:

<div id="go_top">go to top</div>

和CSS

#go_top {
position: fixed;
right: 2em;
bottom: 2em;
color: #000;
background-color: rgba(167, 204, 35, 0.6);
font-size: 12px;
padding: 1em;
cursor: pointer;
display: none;
}
#go_top:hover {
color: #000;
background-color: rgba(167, 204, 35, 1);
}

因此,我设置了以下jquery:

$(document).ready(function() {
$(window).scroll(function() {
    if ($(this).scrollTop() > 200) {
        $('#go_top').fadeIn(200);
    } else {
        $('#go_top').fadeOut(100);
        }
}


});

但它不起作用。 div不会显示:(

4 个答案:

答案 0 :(得分:2)

$(document).ready(function() {
$(window).scroll(function() {
    if ($(this).scrollTop() > 200) {
        $('#go_top').fadeIn(200);
    } else {
        $('#go_top').fadeOut(100);
        }
}); // ')' is missing here**      
});

您的功能中缺少')'

答案 1 :(得分:0)

使用$(document).scrollTop();而不是$(this).scrollTop()

$(document).scroll(function () { alert($(document).scrollTop()) });

答案 2 :(得分:0)

您的代码缺少);并且错误只有scrolltop返回值试试这个

$(document).ready(function () {
    $(window).scroll(function () {
        console.log($(this).scrollTop())
        if ($(this).scrollTop() > 100) { // not px it returns value
            $('#go_top').fadeIn(100);
        } else {
            $('#go_top').fadeOut(100);
        }
    }); // here you must close
});

DEMO(滚动并检查)

答案 3 :(得分:0)

试试这个,

$(document).ready(function() {
    $(window).scroll(function() {
        if ( $(this).scrollTop() > 200) {
            $('#go_top').fadeIn(100);
        } else {
            $('#go_top').fadeOut(100);
            }     

    });    
});

你缺少一个右大括号并从200

中移除px