如何在jquery中知道滚动条何时到达浏览器的中心?

时间:2011-11-19 16:27:32

标签: jquery

我如何知道浏览器何时到达浏览器的中心?当滚动条到达浏览器的中心而不是到达浏览器的末尾时,我需要加载内容。

3 个答案:

答案 0 :(得分:4)

示例1 - 到达页面中间时加载内容

在滚动窗口时,使用jQuery .scroll()方法事件来触发事件。

从那里你可以简单地使用.scrollTop()获取浏览器中与页面顶部相关的当前位置,同时使用.height()获取窗口的最大高度并除以2获得中心点。

一旦.scrollTop()通过中心点,您就找到了中间点。

$(window).scroll(function() {
    if ($(window).scrollTop()  > $(window).height() / 2)
    {
        // middle of page hit, load extra content here
        alert('You are in the middle of the page');

        // Uncomment out the line below to unbind the scroll event if the 
        // execution of this code is only desired once.
        // $(this).unbind('scroll');
    }
});

Fiddle Demo


示例2 - 当标识元素滚动到视图中时加载内容(这更类似于Facebook的工作方式,它们在页面上有一个“加载更多”元素,当它滚动到视图中时表示您到达内容的末尾并加载更多内容。

您可以使用的另一种方法是使用此功能

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

在此回答中Scott Dowding Check if element is visible after scrolling

可用于检测元素在浏览器查看区域内何时可见。使用这种方法,您可以在页面的底部/中间放置一个元素,然后再次使用.scroll()在滚动时触发事件。

当该元素进入视图时,触发您的代码以加载更多内容或您想要做的任何事情。

$(window).scroll(function () {
    if (isScrolledIntoView($('#loadmorecontent')))
    {
        // element has been scrolled into view, load extra contents here
        alert('element scrolled into view');

        // Uncomment out the line below to unbind the scroll event if the 
        // execution of this code is only desired once.
        // $(this).unbind('scroll');
    }
});

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

Fiddle Demo

答案 1 :(得分:3)

如果您需要在用户到达页面底部之前加载内容,您可以在客户端屏幕上计算文档的隐藏底部高度,然后如果文档的底部高度在设定范围内,您可以启动你的脚本如下例所示(使用jQuery):

$(window).scroll(function () {
    //calculating the client's hidden bottom height of the document
    var BottomHeight = $(document).height() - $(window).height() - $(window).scrollTop();
    //set the min value of the document's hidden bottom height
    var minBHeight = 50;

    if (BottomHeight < minBHeight ) {
         alert('Time to load, user is within scroll range!');
        }
});

答案 2 :(得分:0)

首先,您需要页面的总高度,这可以通过了解<body>元素的高度来完成。接下来,您必须知道何时到达页面中心,bodyTotalHeight / 2最后使用scroll上的window object事件来检测用户何时在页面上滚动。滚动条的当前位置由函数scrollTop提供给您。

这里有代码:

var windowElem = $( window );
var mediumHeight =  $( 'body' ).height() / 2;

windowElem.bind( 'scroll', function( e ) {
    if( windowElem.scrollTop() >= mediumHeight ) {
        console.log( 'loading new content...' );
        windowElem.unbind( 'scroll' );
    }
} );