css代码
*{
margin: 0;
padding: 0;
list-style: none;
border: none;
}
img{
vertical-align: top;
}
#main{
position: relative;
}
.box{
float: left;
padding: 15px 0 0 15px;
margin: 0 auto;
}
.box img{
width: 165px;
}
.pic{
padding: 10px;
border: 1px solid #CCCCCC;
border-radius: 5px;
}
Tool代码
(function (w) {
w.Tool = {
$: function (id) {
return document.getElementById(id);
},
scroll: function() {
if (window.pageYOffset !== null) {
return {
"top": window.pageYOffset,
"left": window.pageYOffset
};
} else if (document.compatMode === "CSS1Compat") {
return {
"top": document.documentElement.scrollTop,
"left": document.documentElement.scrollLeft
};
} else {
return {
"top": document.body.scrollTop,
"left": document.body.scrollLeft
};
}
}
};
})(window);
瀑布流js代码
window.addEventListener('load',function (ev) {
waterfull('main', 'box');
var timer1 = null;
window.addEventListener('scroll',function (ev1) {
clearTimeout(timer1);
timer1 = setTimeout(function () {
if (check()){
var dataA = [
{"src" : "image/img01.jpg"},
{"src" : "image/img02.jpg"},
{"src" : "image/img03.jpg"},
{"src" : "image/img04.jpg"},
{"src" : "image/img05.jpg"},
{"src" : "image/img06.jpg"},
{"src" : "image/img07.jpg"},
];
for(var i = 0; i < dataA.length; i++){
var newbox = document.createElement('div');
newbox.className = 'box';
Tool.$('main').appendChild(newbox);
var newpic = document.createElement('div');
newpic.className = 'pic';
newbox.appendChild(newpic);
var newimg = document.createElement('img');
newimg.src = dataA[i].src;
newpic.appendChild(newimg);
}
waterfull('main', 'box');
}
},200)
});
var timer= null;
window.addEventListener('resize',function () {
clearTimeout(timer);
timer = setTimeout(function () {
waterfull('main','box');
},200);
})
});
function waterfull(parent, child) {
var allbox = Tool.$(parent).getElementsByClassName(child);
var boxwidth = allbox[0].offsetWidth;
var W = document.body.clientWidth || document.documentElement.clientWidth;
var cols = parseInt( W / boxwidth);
Tool.$(parent).style.width = cols * boxwidth + 'px';
var heightA = [], boxheight = 0, minheight = 0, minindex = 0;
for (var i = 0; i < allbox.length; i++){
boxheight = allbox[i].offsetHeight;
if (i < cols){
heightA.push(boxheight);
allbox[i].style = '';
}else{
minheight = _.min(heightA);
minindex = getindex(heightA,minheight);
allbox[i].style.position = 'absolute';
allbox[i].style.left = minindex * boxwidth + 'px';
allbox[i].style.top = minheight + 'px';
heightA[minindex] += boxheight;
}
}
}
function getindex(arr, val) {
for (var i = 0; i < arr.length; i++){
if (arr[i] === val){
return i;
}
}
}
function check() {
var allbox = Tool.$('main').getElementsByClassName('box');
var lastbox = allbox[allbox.length - 1];
var lastheight = lastbox.offsetHeight / 2 + lastbox.offsetTop;
var height = document.body.clientHeight || document.documentElement.clientHeight;
var Gheight = Tool.scroll().top;
return lastheight <= height + Gheight;
}