您的位置:首页 > Web前端 > JavaScript

js滚动页面加载内容

2015-12-31 17:18 459 查看
要实现滚动条滚到底部自动加载后续内容到内容到底部的功能,用jQuery非常方便的,只要知道什么时候滚动到了底部就好办了。

 

Js代码  


$(document).scrollTop() //获取垂直滚动条到顶部的距离  

$(document).height()//整个网页的高度  

$(window).height()//浏览器窗口的高度  

 

 

文档的高度减去窗口的高度就是滚动条可滚动的范围了。那么

Js代码  


$(window).scrollTop() + $(window).height()  >= $(document).height()  

 

 

滚动条就到底部了,我们只要在$(window).scroll()中判断和加载内容就可以了:

Js代码  


$(function(){  

  $(window).scroll(function() {  

      //当内容滚动到底部时加载新的内容  

      if ($(this).scrollTop() + $(window).height() + 20 >= $(document).height() && $(this).scrollTop() > 20) {  

          //当前要加载的页码  

          LoadPage(currPage);  

      }  

  });  

});  

 

 

代码中的20是我设置的偏移量,如果底部有其它内容,要在看到底部内容时就加载,而不是必须滚动到底部,就需要这个偏移量了,$(this).scrollTop() > 20是为了不让页面还没有滚动就触发加载;至于页面要加载的内容当然是AJAX处理了,都在LoadPage()中处理就行了!

 

源自:http://www.playcode.cn/jquery-shi-xian-gun-dong-dao-di-bu-zi-dong-jia-zai-nei-rong-gun-dong-fan-ye.html

 

新浪微博网页自动底部加载的效果很酷吧?其实这种叫做“无限滚动的翻页技术”,当你页面滑到列表底部时候无需点击就自动加载更多的内容。

 

其实有很多jQuery的插件都已经实现了这个效果,我们来介绍几个吧!

 

1、jQuery ScrollPagination

jQuery ScrollPagination plugin 是一个jQuery 实现的支持无限滚动加载数据的插件。

地址:http://andersonferminiano.com/jqueryscrollpagination/

他的demo下载:http://andersonferminiano.com/jqueryscrollpagination/jqueryscrollpagination.zip

 

实例代码:

Js代码  


$(function(){  

$('#content').scrollPagination({  

'contentPage': 'democontent.html', // the url you are fetching the results  

'contentData': {}, // these are the variables you can pass to the request, for example: children().size() to know which page you are  

'scrollTarget': $(window), // who gonna scroll? in this example, the full window  

'heightOffset': 10, // it gonna request when scroll is 10 pixels before the page ends  

'beforeLoad': function(){ // before load function, you can display a preloader div  

$('#loading').fadeIn();  

},  

'afterLoad': function(elementsLoaded){ // after loading content, you can use this function to animate your new elements  

$('#loading').fadeOut();  

var i = 0;  

$(elementsLoaded).fadeInWithDelay();  

if ($('#content').children().size() > 100){ // if more than 100 results already loaded, then stop pagination (only for testing)  

$('#nomoreresults').fadeIn();  

$('#content').stopScrollPagination();  

}  

}  

});  

// code for fade in element by element  

$.fn.fadeInWithDelay = function(){  

var delay = 0;  

return this.each(function(){  

$(this).delay(delay).animate({opacity:1}, 200);  

delay += 100;  

});  

};  

});  

 

2、 jQuery Screw

Screw (scroll + view) 是一个 jQuery 插件当用户滚动页面的时候加载内容,是一个无限滚动翻页的插件。

官方地址:https://github.com/jasonlau/jQuery-Screw

 

3. AutoBrowse jQuery Plugin

Autobrowse jQuery Plugin 插件在用户滚动页面的时候自动通过 Ajax 加载更多内容,使用浏览器内置缓存。

官方地址:https://github.com/msjolund/jquery-esn-autobrowse

 源自:http://www.makeyuan.com/2014/02/21/1080.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery