如何使用Javascript检测垂直滚动条的位置

3
if  ($(window).scrollTop() == $(document).height() - $(window).height()){

当滚动条到达末尾时,这个语句将返回true。

好的,

那么我怎么知道它是在80%(还剩20%)???

我正在尝试像这样的表达式:

if  ($(window).scrollTop()*2 == $(document).height() - $(window).height()){  // at the middle?
if  ($(window).scrollTop() == ($(document).height() - $(window).height())+100){    /// 100px left?

但是它们中没有一个返回true,你有什么想法吗?提前感谢你!
1个回答

1

编辑过的

看这里:http://jsfiddle.net/CoolEsh/aQcBZ/7/

HTML

<div style="height:400px;">1 div</div>
<div style="height:300px;">2 div</div>
<div style="height:400px;">3 div</div>
<div style="height:200px;">4 div</div>
<div style="height:600px;">5 div</div>

JS

var handlerObj = {

    _pageAboveCenter: null,

    init: function()
    {
        handlerObj._pageAboveCenter = handlerObj._isPageAboveCenter();

        $( window ).scroll( handlerObj._handleScroll );
    },

    _handleScroll: function()
    {
        var curentPositionAboveCenter = handlerObj._isPageAboveCenter();
        if ( curentPositionAboveCenter != handlerObj._pageAboveCenter )
        {
            handlerObj._centerIntersection();
            handlerObj._pageAboveCenter = curentPositionAboveCenter;
        }

    },

    _centerIntersection: function()
    {
        console.log( "Center intersected!" ); // this is for firebug console
    },

    _isPageAboveCenter: function()
    {
        if ( ( Math.floor( $( window ).height() / 2 ) + $(window).scrollTop() ) > ( Math.floor( $(document).height() / 2 ) ) )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

$( document ).ready( handlerObj.init );

这个例子即使有人快速滚动也能正常工作。我在页面加载时初始化变量_pageAboveCenter。然后在滚动事件中,我检查当前位置(它是在中心上方还是下方),如果curentPositionAboveCenterhandlerObj._pageAboveCenter的值不同,则调用方法表示已经相交于中心。


需要设置一些间隔,例如4或6个像素,以便我们检测滚动条是否在页面中央。您可以更改条件末尾的-2和+2来增加或减少此间隔。 - CoolEsh
这个有点奇怪!它能正常工作,但是如果刷新,它并不总是起作用!这怎么可能呢? - Toni Michel Caubet
非常感谢!我尝试了+10和-10,但仍然遇到了同样的问题...那+50-50呢? - Toni Michel Caubet
非常感谢您的帮助。但最终我意识到这对我来说不是一个选项。因为当您向上滚动时,它也被调用,这会破坏我的东西...但将来还是好知道的 ;) - Toni Michel Caubet
但是您可以更新我的代码,以便仅通过从文档开头滚动到文档结尾来检查文档中心,就像这里:http://jsfiddle.net/CoolEsh/aQcBZ/8/ - CoolEsh
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接