javascript 瀑布流
现在图片网与商城流行一种叫“瀑布流”的布局,我们公司也不小心得了“流行性感冒”,要搞这个。于是我就写了一个,现在再用我的框架mass重写一下,发布出来,顺便宣传一下我的框架。
瀑布流其实没什么东西,就是列布局与无限拖的结合。由于要支持IE6就没有CSS3,直接对列进行绝对定位。列就是一个DIV。然后就是列中每个板块的添加问题,我管它为砖头。每添加一块砖头前,比较一下哪列最短,就往哪里塞。最后就是无限拖,太easy了。加之,我的框架对样式,事件等设置非常简单,比jQuery更方便。
下面就是源码,用到了并行加载技术,预设时加载了random,ready,css,event这几个模块,它们就会自行加载其依赖模块了。
require("ready,random,css,event",function($, random){
//容器的CSS表达式,列数,每列的宽度
var Waterfall = function(expr, col, colWidth){
//构建整体轮廓
var container = this.container = $(expr);
var pw = container.width();//容器的宽
var gw = (pw - col * colWidth)/(col-1);//列间距离
this.colWidth = colWidth;
this.cols = [];
for(var i = 0; i < col ; i++){//随机生成列
this.cols[i] = $("<div class='waterfall' />").css({
position: "absolute",
top: 0,
left: (colWidth + gw) * i,
width: colWidth,
backgroundColor: random.hex()
}).appendTo(container);
}
}
Waterfall.prototype = {
//添加板块
addBlocks : function(){
for(var i = 0; i < 40; i++){//随机生成40个板砖
$("<div class='waterfall_block' />").css({
margin: 5,
width: this.colWidth - 10 ,
height: random.num(80, 300),
backgroundColor: random.hex()
}).appendTo( this.whichCol() );
}
},
//计算出最短的栏栅
whichCol:function(el, ret, h){
for(var i = 0, shortest = 0; el = this.cols[i]; i++){
h = el.height();
if(i == 0){
shortest = h;
ret = el;
}
if(h < shortest ){
shortest = h;
ret = el;
}
}
return ret;
}
};
var waterfall = new Waterfall("body",4,300)
waterfall.addBlocks();
$(window).scroll(function(){
var clientHeight = $(window).height(),
scrollTop = $(window).scrollTop(),
scrollHeight = $(document).height();
if(clientHeight + scrollTop >= scrollHeight ){
waterfall.addBlocks();
}
})
})
源码放于github中。
IE下如果报错,请它刷新页面
最后附上微博上对它的评论:Pinterest创造的瀑布流样式,有几个预设前提:1、图片极重要,文字不重要;2、用户浏览无明确目的,对复杂的索引无依赖性;3、图片整体美观度较高。因此恰恰适合Pinterest这样的“好图挖掘与收藏网站”。最近几个月国内跟风瀑布流,也太盲目了些。
机器瞎学/数据掩埋/模式混淆/人工智障/深度遗忘/神经掉线/计算机幻觉/专注单身二十五年
浙公网安备 33010602011771号