前言:
现在很多内容型网站都会采用瀑布流布局来实现内容展示,包括文章类及图片类,我们可以自己动手来编写属于我们自己的瀑布流插件。
效果:
CSS部分:
*
{
margin: 0;
padding: 0;
}
body {
font-family: "Droid Serif","Helvetica Neue",Helvetica,Arial,sans-serif;
font-size: 14px;
}
.clearfix:after{
content: "";
display: block;
clear: both;
}
input,
button,
select,
textarea{
outline:none;border: none;
}
a{
text-decoration: none;
}
ul,
li{
list-style: none;
}
img{
border: none;
}
.wrap {
position: relative;
min-width: 440px;
width: 90%;
margin: 0 auto;
}
.item {
width: 200px;
margin: 10px;
position: absolute;
transition: all .6s ease-out;
font-size: 50px;
color: #fff;
text-align: center;
}
HTML部分:
<div class="wrap"></div>
JS部分:
var WaterFall = {
init:
function(){
this.addItem();
this.layout();
this.resize();
},
addItem:
function(){
var wrap = $(
'.wrap');
var item =
'';
for (
var i =
0; i <
20; i++) {
item +=
'<div class="item" style="height:'+
parseInt(
Math.random() *
100 +
230)+
'px;background-color:'+
this.getRandColor()+
'">'+i+
'</div>';
}
wrap.append(item);
},
layout:
function(){
var elHeight = [];
var countWidth =
Math.floor( $(
'.wrap').width() / $(
'.item').width());
for (
var i =
0; i < countWidth; i++) {
elHeight[i] =
0;
}
$(
'.item').each(
function(index, el) {
var minValue =
Math.min.apply(
null, elHeight);
var minIndex = elHeight.indexOf(minValue)
$(
this).css({
top: elHeight[minIndex],
left: $(
this).outerWidth(
true) * minIndex
})
elHeight[minIndex] += $(
this).outerHeight(
true);
});
},
resize:
function(){
$(window).resize(
function() {
WaterFall.layout();
});
},
getRandColor:
function(){
var str =
'1234567890abcdef';
var colorStr =
'#';
for(
var i =
0; i <
6; i++){
colorStr += str[
Math.floor(
Math.random() * str.length) ];
}
return colorStr;
}
}
WaterFall.init();