/** * * @authors Your Name (you@example.org) * @date 2014-10-16 16:42:50 * @version $Id$ */ window.onload = function() { waterfall(); var dataInit = { "data": [{ "src": "6.jpg" }, { "src": "7.jpg" }, { "src": "8.jpg" }] }; // 检查数据是否撑满页面 load(); window.onscroll = function() { var flag = checkLoadImage(); if (flag) { load(); } } } function checkShow() { var oParent = document.getElementById('main'); var boxs = getByClass(oParent, 'box'); // 取得页面高度 var windowH = document.body.clientHeight || document.documentElement.clientHeight; // 最后一个对象的高度 + top < windowH 就加载 return (boxs[boxs.length - 1].offsetHeight + boxs[boxs.length - 1].offsetTop) < windowH ? true : false; } function load() { // 加载 var main = document.getElementById('main'); for (var i = 0; i < dataInit.data.length; i++) { var box = document.createElement('div'); box.className = 'box'; main.appendChild(box); var pic = document.createElement('div'); pic.className = 'pic'; box.appendChild(pic); var img = document.createElement('img'); img.src = "images/" + dataInit.data[i].src; pic.appendChild(img); } waterfall(); } function checkLoadImage() { var scTop = document.body.scrollTop || document.documentElement.scrollTop; var screenH = document.body.clientHeight || document.documentElement.clientHeight; // 取得当前列数 var oParent = document.getElementById('main'); var oBoxs = getByClass(oParent, 'box'); var hh = oBoxs[oBoxs.length - 1].offsetHeight + oBoxs[oBoxs.length - 1].offsetTop; var flag = hh - 20 < (scTop + screenH) ? true : false; return flag; } function waterfall() { var oParent = document.getElementById('main'); var boxs = getByClass(oParent, 'box'); var boxW = boxs[0].offsetWidth; var clientW = document.body.clientWidth || document.documentElement.clientWidth; var cols = Math.floor(clientW / boxW); oParent.style.cssText = 'width:' + boxW * cols + 'px;margin:auto;'; // 行数组 var hArr = []; for (var i = 0; i < boxs.length; i++) { if (i < cols) { hArr.push(boxs[i].offsetHeight); } else { var minH = Math.min.apply(null, hArr); var minIndex = getIndex(hArr, minH); boxs[i].style.cssText = 'position:absolute;left:' + minIndex * boxW + 'px;top:' + minH + 'px;'; hArr[minIndex] = minH + boxs[i].offsetHeight; } } } function getIndex(arr, value) { for (var p in arr) { if (arr[p] == value) { return p; } } } function getByClass(parent, name) { var elements = []; var list = parent.getElementsByTagName('*'); for (var i = 0; i < list.length; i++) { if (list[i].className == name) { elements.push(list[i]); } } return elements; }
<body> <div id="main"> <div class="box"> <div class="pic"> <img src="images/0.jpg"> </div> </div> <div class="box"> <div class="pic"> <img src="images/1.jpg"> </div> </div> <div class="box"> <div class="pic"> <img src="images/2.jpg"> </div> </div> <div class="box"> <div class="pic"> <img src="images/3.jpg"> </div> </div> </div> </body>
老师你好,我发现一个问题,我添加了一个检查数据是否撑满页面load();方法目的是为了在初始化的时候如果图片没有撑满就再加载新的图片,可是发现模拟的新数据加载到页面后无法计算高度,图片是后渲染的。