css
#content {
width: 1000px;
height: 100vh;
}
#content ul {
width: 100%;
}
#content ul li {
width: 23%;
float: left;
margin: 20px 1%;
list-style: none;
}
#content ul li div {
margin: 10px 0;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
#content ul li p img {
width: 100%;
}
html
<div id="content"></div>
js
const data = ["http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/1.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/2.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/3.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/4.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/5.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/6.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/7.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/8.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/1.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/2.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/3.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/4.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/5.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/6.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/7.jpg",
"http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201507/jiaoben3505/picture/8.jpg",
];
/**
* @function 圖片瀑布流方法
* @data 圖片數據
* @obj 容器對象
* @liNum 列數量
*/
const getImgFlow = (data = [], obj = document.getElementsByTagName('body')[0], liNum = 4) => {
//判斷容器內是否存在ul
let objUl = obj.getElementsByTagName('ul');
let _ul = objUl.length == 0 ? document.createElement('ul') : objUl;
let _li = obj.getElementsByTagName('li');
let _i = _li.length % liNum;
let _is = objUl.length == 0 && _li.length == 0;
if (_is) {
for (let i = 0; i < liNum; i++) {
_ul.appendChild(document.createElement('li'));
}
obj.appendChild(_ul)
}
data.forEach((value, index) => {
let _div = document.createElement('div');
_div.innerHTML = `<div><p><img src="${value}" /></p></div>`
if (_i < 4 && _is) {
_li[_i].appendChild(_div);
} else {
//哪個列最短,就先加那個
let maxTop = 0,
liTop = {};
Object.keys(_li).forEach((item, i) => {
let theLi = _li[item];
let liDiv = theLi.getElementsByTagName('div');
let _top = liDiv[liDiv.length - 1].offsetTop;
liTop[_top] = item;
maxTop = i == 0 ? _top : _top > maxTop ? maxTop : _top;
});
_li[liTop[maxTop]].appendChild(_div);
}
_i++;
});
}
let _content = document.getElementById('content');
getImgFlow(data, _content);
window.onscroll = function (e) {
if (document.getElementsByTagName('html')[0].scrollHeight - window.innerHeight == window.scrollY) {
getImgFlow(data, _content);
}
}
效果: