连续或无限滚动,在靠近页面底部时加载更多内容

时间:2012-08-21 12:14:40

标签: javascript ajax dynamic scroll

我被要求设计一个随着用户不断滚动而不断扩展的网站。我在JavaScript方面经验丰富,但我从未遇到任何可以解决这个问题的事情。使用这种技术的热门网站是Twitter和Facebook。我知道我将需要AJAX来加载更多内容,但我不确定浏览器将如何知道用户正在接近页面底部?

3 个答案:

答案 0 :(得分:5)

您可以使用三个JavaScript函数执行此操作。第一个是window.scrollY。此功能将为您提供网页上的高度位置(即如果您位于顶部,则为0,向下滚动时会增加)。

第二个是document.body.scrollHeight这将为您提供窗口的总高度,包括滚动。

最终功能是window.innerHeight。这为您提供了用户可以看到的窗口高度(可见部分的高度)。

使用这三个功能,您可以获得浏览器窗口的顶部和底部位置以及整个页面的大小。从那里你可以找出用户在页面上的位置,并确定页面是否应该展开。

答案 1 :(得分:0)

这是一个基于Patrick548答案的假AJAX调用的自包含示例(它得到了我的支持)。在Chrome中测试过。

这并不能说明用户滚动到页面顶部,但支持应该很容易添加。

<!doctype html>
<html lang="en">
    <head>
        <title>Infinite Scroll Test</title>
        <style>
#articles {
    width: 200px;
}

.article {
    display: block;
    border: 1px solid #000;
    border-radius: 4px;
    background-color: #eee;
    margin-bottom: 1em;
}
        </style>

        <script>
var articleCounter = 0;

function fakeAjaxCall(cb) {
    var createNewArticle = function() {
            return {
                id: ++articleCounter
              , author: 'Foo Bar'
              , text: 'Lorem ipsum and all that jazz.'
            };
        }
      , articles = []
    ;

    for (var i=0; i<10; i++) {
        var fakeArticle = createNewArticle();
        articles.push(fakeArticle);
    }

    // call the fake success handler with the fake data
    if (cb && typeof(cb == 'function')) cb({ articles: articles });
}

function appendFakeData(data) {
    if (! data && data.articles) return;

    for (var i=0; i<data.articles.length; i++) {
        var article = data.articles[i]
        document.querySelector('#articles').innerHTML +=
            '<div class="article">[' + article.id + '] ' + article.author + ' sez:<br>' + article.text + '</div>';
   }

    var articleCount = document.querySelectorAll('.article').length;
    console.log('article count is now: ' + articleCount);

    if (articleCount > 50) removeFirstTenArticles();
}

function removeFirstTenArticles() {
    var articlesEl    = document.querySelector('#articles')
      , firstChild    = articlesEl.firstChild
      , articleStyle  = window.getComputedStyle(document.querySelector('.article'))
      , articleHeight = parseInt(articleStyle.height) + parseInt(articleStyle.marginBottom);
    ;

    // remove the first 10 articles in the container
    for (var i=0; i<10; i++) {
        articlesEl.removeChild(firstChild);
        firstChild = articlesEl.firstChild;
    }

    // scroll back to where the new articles were inserted
    document.body.scrollTop -= (10 * articleHeight);
}

window.addEventListener('load', function() {
    document.body.scrollTop = 0; // start at the top
    fakeAjaxCall(appendFakeData);
});

document.addEventListener('scroll', function(evt) {
    // if distance from bottom of page is zero, grab and append more articles
    if (document.body.scrollHeight - (window.innerHeight+window.scrollY) == 0) {
        console.log('getting more data...');
        fakeAjaxCall(appendFakeData);
    }
});
        </script>
    </head>

    <body>
        <section id="articles"></section>
    </body>
</html>

答案 2 :(得分:0)

http://www.youtube.com/watch?v=eziREnZPml4

<script type="text/javascript">
function yHandler();
var wrap = document.getElementById('wrap');
    var contentHeight = wrap.offsetHeight;
var yOffset = window.pageYOffset; 
var y = yOffset + window.innerHeight;
if(y >= contentHeight){
    // Ajax call to get more dynamic data goes here
    wrap.innerHTML += '<div class="newData"></div>';
}
var status = document.getElementById('status');
status.innerHTML = contentHeight+" | "+y;
}

window.onscroll = yHandler;
</script>