#114 Endless Page

本文介绍如何在Rails应用中实现无限滚动效果,通过分页加载产品列表,利用JavaScript监测滚动位置并自动加载更多内容。
Ever wondered how some sites seem to have endless scrolling page with no pagination? Find out how easy it is to do this in Rails in this episode.
# products_controller.rb
def index
@products = Product.paginate(:page => params[:page], :per_page => 15)
end

# index.js.rjs
page.insert_html :bottom, :products, :partial => @products
if @products.total_pages > @products.current_page
page.call 'checkScroll'
else
page[:loading].hide
end

# application_helper.rb
def javascript(*args)
content_for(:head) { javascript_include_tag(*args) }
end

<!-- index.html.erb -->
<% title "Products" %>
<% javascript :defaults, 'endless_page' %>

<div id="products">
<%= render :partial => @products %>
</div>
<p id="loading">Loading more page results...</p>

// endless_page.js
var currentPage = 1;

function checkScroll() {
if (nearBottomOfPage()) {
currentPage++;
new Ajax.Request('/products.js?page=' + currentPage, {asynchronous:true, evalScripts:true, method:'get'});
} else {
setTimeout("checkScroll()", 250);
}
}

function nearBottomOfPage() {
return scrollDistanceFromBottom() < 150;
}

function scrollDistanceFromBottom(argument) {
return pageHeight() - (window.pageYOffset + self.innerHeight);
}

function pageHeight() {
return Math.max(document.body.scrollHeight, document.body.offsetHeight);
}

document.observe('dom:loaded', checkScroll);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值