原生的javascript图片瀑布流实现,具体代码如下:
(function($){
$.fn.niceWall = function(options){
$.fn.niceWall.defaults = {
"wrap":"body",
"width":200,
"gap":10,
"url":"",
"count":null,
"callback":null
};
var opts = $.extend({},$.fn.niceWall.defaults ,options || {});
//
return this.each(function(){
var $this = $(this);
var colspanW = opts.width + opts.gap;
var arrX = [];
var arrY = [];
var iPage = 0;
var iBtn = true;
var colspan = Math.floor($(opts.wrap).innerWidth() / colspanW);
//
function setLayer(){
colspan = Math.floor($(window).innerWidth() / colspanW);
$this.css("width",colspanW * colspan - opts.gap);
for(var i = 0; i < colspan;i++){
arrX[i] = colspanW * i;
arrY[i] = 0;
}
};
setLayer();
//
function render(){
if(!iBtn) return;
iPage++;
iBtn = false;
$.getJSON(opts.url,{page:iPage},function(data){
$.each(data,function(index,element){
console.log(element)
var oDiv = $("<div class='nice-wall'><p></p></div>");
var oImg = $("<img>");
var iH = (element.height / element.width)* opts.width;
oDiv.css({
"position":"absolute",
"width":opts.width + "px",
"height":iH + "px"
});
var _index = getMin();
oDiv.css({
"left":arrX[_index] + "px",
"top":arrY[_index] + "px"
});
arrY[_index] += iH + opts.gap;
//
oDiv.append(oImg);
$this.append(oDiv);
var hookImg = new Image();
hookImg.src = element.preview;
hookImg.onload = function(){
oImg.attr({
"src":this.src,
"href":element.image
});
};
//
iBtn = true;
});
//
if(opts.callback){
opts.callback();
}
});
};
render();
//
function getMin(){
var v = arrY[0];
var _index = 0;
for(var i = 1;i < arrY.length;i++){
if(arrY[i] < v){
v = arrY[i];
_index = i;
}
}
return _index;
};
//
$(window).off("scroll",srcollFn).on("scroll",srcollFn);
//
function srcollFn(){
var stp = $(window).scrollTop() + $(window).innerHeight();
var dH = $(document).height();
var _index = getMin();
if(arrY[_index] + 50 < stp ){
render();
}
};
//
$(window).on("resize",function(){
arrX = [];
arrY = [];
setLayer();
//
$this.find(".nice-wall").each(function(){
var _index = getMin();
$(this).animate({
"left":arrX[_index] + "px",
"top":arrY[_index] + "px"
},400);
arrY[_index] += $(this).height() + opts.gap;
});
});
});
}
})(jQuery);
更多信息请查看IT技术专栏