使用jquery插件waterfall实现自动加载下一页

本文内容主要摘自:<http://wlog.cn/waterfall/index-zh.html>

开发时请参照原文,本文是在做的过程中遇到的一些问题进行补充说明:

Waterfall

下载

下载waterfall插件最新版本。

使用

html:

<div id="container"></div>

这段代码是作为加载内容的容器。

引入jquery,handlebars和waterfall(注:waterfall默认返回json格式数据并使用handlebars模板渲染json数据,你也可以在options中配置使用其它javascript模板如mustache解析json数据或者直接返回html):

原文中加载部分使用的是handlebars插件,不过我不想再多引入插件还是直接使用json或者html

<script src="/path/jquery.min.js"></script>
<!-- <script src="/path/handlebars.js"></script>不引入 -->
<script src="/path/waterfall.min.js"></script>

template:这段也不需要了

<script id="waterfall-tpl" type="text/x-handlebars-template">
    //template content
</script>

我使用的是nodejs的ejs模板,是直接从原有的页面上抠出来一块用来动态加载,使用json的话还要写这么一堆字符串,所以干脆使用html格式的加载,其他语言的大同小异,morenews.html数据:

<%newsList.forEach(function(item,index){%>
<div class="news-list-group-item">
    <img src="<%=download_website+item.picture_mini%>" alt="">
    <div>
        <a href="/portal/news/<%=item.news_id%>" ><strong><%=item.title_zh%></strong></a>
        <p><%=item.summary_zh%></p>
        <p class="news-item-basic"><span class="news-date"><%=item.release_date || item.create_date%></span><span class="news-look">阅读量:<span><%=item.read_count%></span></span></p>
    </div>
</div>
<%})%>

script:

$('#container').waterfall({
	itemCls: 'news-list-group-item', //加载部分的class
	prefix: '',//可以不写
	fitWidth: true, 
	colWidth: 240, 
	gutterWidth: 10,
	gutterHeight: 10,
	align: 'center',//加载部分的对齐样式,可能需要配置
	minCol: 1, 
	maxCol: undefined, 
	maxPage: undefined, 
	bufferPixel: -50, 
	containerStyle: {
		position: 'relative'
	},
	resizable: true, 
	isFadeIn: false,
	isAnimated: false,
	animationOptions: { 
	},
	isAutoPrefill: true,
	checkImagesLoaded: true,
	path: undefined,//加载部分请求地址
	dataType: 'json', //我使用的是html
	params: {}, 
	
	loadingMsg: '<div style="text-align:center;padding:10px 0; color:#999;"><img src="data:image/gif;base64,R0lGODlhEAALAPQAAP///zMzM+Li4tra2u7u7jk5OTMzM1hYWJubm4CAgMjIyE9PT29vb6KiooODg8vLy1JSUjc3N3Jycuvr6+Dg4Pb29mBgYOPj4/X19cXFxbOzs9XV1fHx8TMzMzMzMzMzMyH5BAkLAAAAIf4aQ3JlYXRlZCB3aXRoIGFqYXhsb2FkLmluZm8AIf8LTkVUU0NBUEUyLjADAQAAACwAAAAAEAALAAAFLSAgjmRpnqSgCuLKAq5AEIM4zDVw03ve27ifDgfkEYe04kDIDC5zrtYKRa2WQgAh+QQJCwAAACwAAAAAEAALAAAFJGBhGAVgnqhpHIeRvsDawqns0qeN5+y967tYLyicBYE7EYkYAgAh+QQJCwAAACwAAAAAEAALAAAFNiAgjothLOOIJAkiGgxjpGKiKMkbz7SN6zIawJcDwIK9W/HISxGBzdHTuBNOmcJVCyoUlk7CEAAh+QQJCwAAACwAAAAAEAALAAAFNSAgjqQIRRFUAo3jNGIkSdHqPI8Tz3V55zuaDacDyIQ+YrBH+hWPzJFzOQQaeavWi7oqnVIhACH5BAkLAAAALAAAAAAQAAsAAAUyICCOZGme1rJY5kRRk7hI0mJSVUXJtF3iOl7tltsBZsNfUegjAY3I5sgFY55KqdX1GgIAIfkECQsAAAAsAAAAABAACwAABTcgII5kaZ4kcV2EqLJipmnZhWGXaOOitm2aXQ4g7P2Ct2ER4AMul00kj5g0Al8tADY2y6C+4FIIACH5BAkLAAAALAAAAAAQAAsAAAUvICCOZGme5ERRk6iy7qpyHCVStA3gNa/7txxwlwv2isSacYUc+l4tADQGQ1mvpBAAIfkECQsAAAAsAAAAABAACwAABS8gII5kaZ7kRFGTqLLuqnIcJVK0DeA1r/u3HHCXC/aKxJpxhRz6Xi0ANAZDWa+kEAA7" alt=""><br />Loading...</div>',
	
	state: { 
		isDuringAjax: false, 
		isProcessingData: false, 
		isResizing: false,
		curPage: 1 
	},

	// callbacks
	callbacks: {
		/*
		 * loadingStart
		 * @param {Object} loading $('#waterfall-loading')
		 */
		loadingStart: function($loading) {
			$loading.show();
			//console.log('loading', 'start');
		},
		
		/*
		 * loadingFinished
		 * @param {Object} loading $('#waterfall-loading')
		 * @param {Boolean} isBeyondMaxPage
		 */
		loadingFinished: function($loading, isBeyondMaxPage) {
			if ( !isBeyondMaxPage ) {
				$loading.fadeOut();
				//console.log('loading finished');
			} else {
				//console.log('loading isBeyondMaxPage');
				$loading.remove();
			}
		},
		
		/*
		 * loadingError
		 * @param {String} xhr , "end" "error"
		 */
		loadingError: function($message, xhr) {
			$message.html('Data load faild, please try again later.');
		},
		
		/*
		 * renderData
		 * @param {String} data
		 * @param {String} dataType , "json", "jsonp", "html"
		 */
		renderData: function (data, dataType) {
			var tpl,
				template;
				
			if ( dataType === 'json' ||  dataType === 'jsonp'  ) { // json or jsonp format
				tpl = $('#waterfall-tpl').html();
				template = Handlebars.compile(tpl);
				
				return template(data);
			} else { // html format
				return data;
			}
		}
	},
	
	debug: false
});

options

itemClsString'waterfall-item'瀑布流数据块class
prefixString'waterfall'瀑布流元素前辍
fitWidthBooleantrue是否自适应父元素宽度
colWidthInteger240瀑布流每列的宽度
gutterWidthInteger10数据块水平间距
gutterHeightInteger10数据块垂直间距
alignString'center'数据块相对于容器对齐方式,'align', 'left', 'right'
minColInteger1数据块最小列数
maxColIntegerundefined数据块最多显示列数,默认undefined,最大列数无限制
maxPageIntegerundefined最多显示多少页数据,默认undefined,无限下拉
bufferPixelInteger-50滚动时, 窗口底部到瀑布流最小高度列的距离 > bufferPixel时, 自动加载新数据
containerStyleObject{position: 'relative'}瀑布流默认样式
resizableBooleantrue缩放时是否触发数据重排
isFadeInBooleanfalse新插入数据是否使用fade动画
isAnimatedBooleanfalseresize时数据是否显示动画
animationOptionsObject{}resize动画效果,isAnimated为true时有效
isAutoPrefillBooleantrue当文档小于窗口可见区域,自动加载数据
checkImagesLoadedBooleantrue是否图片加载完成后开始排列数据块。如果直接后台输出图片尺寸,可设置为false,强烈建议从后台输出图片尺寸,设置为false
pathArray, Functionundefined瀑布流数据分页url,可以是数组如["/popular/page/", "/"] => "/popular/page/1/",或者是根据分页返回一个url方法如:function(page) { return '/populr/page/' + page; } => "/popular/page/1/"
dataTypeString'json'瀑布流返回数据格式,'json', 'jsonp', 'html'
paramsObject{}瀑布流数据请求参数,{type: "popular", tags: "travel", format: "json"} => "type=popular&tags=travel&format=json"
loadingMsgHtml见下面代码加载提示进度条,html
callbacksObject见下面代码callback
debugBooleanfalse开启debug

loadingMsg:

'&lt;div style="text-align:center;padding:10px 0; color:#999;">&lt;img src="data:image/gif;base64,R0lGODlhEAALAPQAAP///zMzM+Li4tra2u7u7jk5OTMzM1hYWJubm4CAgMjIyE9PT29vb6KiooODg8vLy1JSUjc3N3Jycuvr6+Dg4Pb29mBgYOPj4/X19cXFxbOzs9XV1fHx8TMzMzMzMzMzMyH5BAkLAAAAIf4aQ3JlYXRlZCB3aXRoIGFqYXhsb2FkLmluZm8AIf8LTkVUU0NBUEUyLjADAQAAACwAAAAAEAALAAAFLSAgjmRpnqSgCuLKAq5AEIM4zDVw03ve27ifDgfkEYe04kDIDC5zrtYKRa2WQgAh+QQJCwAAACwAAAAAEAALAAAFJGBhGAVgnqhpHIeRvsDawqns0qeN5+y967tYLyicBYE7EYkYAgAh+QQJCwAAACwAAAAAEAALAAAFNiAgjothLOOIJAkiGgxjpGKiKMkbz7SN6zIawJcDwIK9W/HISxGBzdHTuBNOmcJVCyoUlk7CEAAh+QQJCwAAACwAAAAAEAALAAAFNSAgjqQIRRFUAo3jNGIkSdHqPI8Tz3V55zuaDacDyIQ+YrBH+hWPzJFzOQQaeavWi7oqnVIhACH5BAkLAAAALAAAAAAQAAsAAAUyICCOZGme1rJY5kRRk7hI0mJSVUXJtF3iOl7tltsBZsNfUegjAY3I5sgFY55KqdX1GgIAIfkECQsAAAAsAAAAABAACwAABTcgII5kaZ4kcV2EqLJipmnZhWGXaOOitm2aXQ4g7P2Ct2ER4AMul00kj5g0Al8tADY2y6C+4FIIACH5BAkLAAAALAAAAAAQAAsAAAUvICCOZGme5ERRk6iy7qpyHCVStA3gNa/7txxwlwv2isSacYUc+l4tADQGQ1mvpBAAIfkECQsAAAAsAAAAABAACwAABS8gII5kaZ7kRFGTqLLuqnIcJVK0DeA1r/u3HHCXC/aKxJpxhRz6Xi0ANAZDWa+kEAA7" alt="">&lt;br />Loading...&lt;/div>'

callbacks:

callbacks: {
    /*
     * ajax请求开始之前
     * @param {Object} loading $('#waterfall-loading')
     */
    loadingStart: function($loading) {
        $loading.show();
    },

    /*
     * ajax请求加载完成
     * @param {Object} loading $('#waterfall-loading')
     * @param {Boolean} isBeyondMaxPage
     */
    loadingFinished: function($loading, isBeyondMaxPage) {
        if ( !isBeyondMaxPage ) {
            $loading.fadeOut();
        } else {
            $loading.remove();
        }
    },

    /*
     * ajax请求出错误
     * @param {String} xhr , "end" "error"
     */
    loadingError: function($message, xhr) {
        $message.html('Data load faild, please try again later.');
    },

    /*
     * 处理ajax返回数方法
     * @param {String} data
     * @param {String} dataType , "json", "jsonp", "html"
     */
    renderData: function (data, dataType) {
        var tpl,
            template;

        if ( dataType === 'json' ||  dataType === 'jsonp'  ) { // json或jsonp格式
            tpl = $('#waterfall-tpl').html();
            template = Handlebars.compile(tpl);

            return template(data);
        } else { // html格式
            return data;
        }
    }
}

method

$('#container').waterfall( 'methodName', [optionalParameters] );

prepend

$('#container').waterfall('prepend', $content, callback);

append

$('#container').waterfall('append', $content, callback);

removeItems

$('#container').waterfall('removeItems', $items, callback);

reLayout

$('#container').waterfall('reLayout', $content, callback);

pause

$('#container').waterfall('pause', callback);

resume

$('#container').waterfall('pause', callback);

option

$('#container').waterfall('option', options, callback);
以上几个方法根据需求使用,比如没有数据的时候,可以查看下面的“没有数据处理”的源码,还有种情况是页面初始化就没有数据,这样会一直有加载的效果,可以加上这样一段代码:
 
var c = $("#container").html().replace(/\ +/g,"").replace(/[\r\n]/g,"");
if(c==""){
    $("#container").append('<p style="color:#FFF; text-align: center">没有数据,请查看其他内容!<a href="javascript:window.history.back()">返回</a></p><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>');
}else {
    $('#container').waterfall({
        itemCls: 'news-list-group-item',

Demos

相关推荐