js仿淘宝/蘑菇街形式,瀑布流效果
2012-11-02 16:29:47 来源:WEB开发网var waterfall_2 = waterfall($("#waterfall_container2"), {url:'./7__.php', tpl:tpl});
//waterfall_2.setActive(false);
</script>
</body>
</html>
/**
* 瀑布流效果JS
*
* @author lixiaogang <858864436@qq.com>
*/
;(function(){
//保存每个选项卡所对应的数据[instance的json结构]
var instances = [], $win = $(window), scroll_top = 0;
/**
* 瀑布流效果入口函数
* @param object el 瀑布流外层的容器的节点对象
* @param json options json对象:
* url:ajax请求路径(必填),
* tpl:html模板(必填),
* selector:ajax数据填充节点的class名称,默认为:.img_container
* max_page:ajax获取最大的页数,默认为:5
*
* @return object setActive:设置是否开启根据窗口下拉比例多次获取函数,false:不开启,true:开启
*/
waterfall = function(el, options) {
if(!options.url || !options.tpl) return;
var instance = {element: el, active: true, loading: true, page: 0, max_page:5};
if(options.max_page) instance = $.extend(instance, {max_page:options.max_page});
instance.options = $.extend({selector: '.img_container'}, options);
instance.children = $(el).find(instance.options.selector);
instance.cols = instance.children.length;
var index = instances.length;
instances[index] = instance;
load(instance);
return {
setActive: function(val) {
instances[index].active = !!val;
}
};
};
//ajax 动态获取数据
function load(instance) {
instance.page++;
if(instance.page > parseInt(instance.max_page)) return;
$.getJSON(instance.options.url, {page:instance.page}, function(data) {
var data_len = data.length, temp = []; //临时保存html
for(var i=0; i<data_len; i++){
var item = data.shift(), index = i % instance.cols;
if('undefined' == typeof temp[index]) temp[index] = '';
temp[index] += instance.options.tpl.replace(/\{\w+\}/g , function(m) {return item[m.substring(1,m.length-1)];});
}
if(0 < temp.length){
for(var i=0; i<instance.cols; i++){
instance.children.eq(i).append(temp[i]);
}
}
instance.loading = false;
});
};
/**
* 窗口绑定事件
* 1. 若 active=false 则 不触发ajax的数据获取
* 2. 若 loading=true 则 表示正在进行ajax数据获取,不进行多次数据获取
*/
$win.scroll( function() {
var temp_scroll_top = $win.scrollTop();
if (temp_scroll_top > scroll_top && ($win.height() + $win.scrollTop()) >= $("body" ).height()-100) {
scroll_top = temp_scroll_top;
$.each(instances, function(i, instance){
if (!instance.active || instance.loading) return;
instance.loading = true;
load(instance);
});
}
});
})();
更多精彩
赞助商链接