为什么是$(window).scrollTop();报告零?

时间:2014-01-29 23:17:30

标签: javascript jquery

我正在尝试在$(window).bind('scroll',function(){})中运行一个函数;这取决于var scrollHeight - 但scrollHeight保持报告0

$(document).ready(function() {

    console.log('hello');
    var scrollHeight = $(window).scrollTop();

    $(window).bind('scroll',function(){
        console.log('scroll height =', scrollHeight)
    });
});

看看小提琴并打开你的控制台,无论你滚动多远,看看scrollHeight = 0。 http://jsfiddle.net/VJ2Z3/

1 个答案:

答案 0 :(得分:4)

jsFiddle Demo

您永远不会更新scrollHeight。因为它只被读取一次,所以每次滚动事件触发时都会获得该常量值。

$(window).bind('scroll',function(){
    //update the value inside of the event handler
    var scrollHeight = $(window).scrollTop();
    console.log('scroll height =', scrollHeight);
});