夏木家的猫
2014-12-28 20:09
window.onload = function(){ imgLocation('container', 'box'); window.onscroll = function(){ var imgData = { "data":[ {"src" : "1.jpg"}, {"src" : "2.jpg"}, {"src" : "3.jpg"}, {"src" : "4.jpg"}, {"src" : "5.jpg"}, {"src" : "6.jpg"} ] }; if(checkFlag()){ var oParent = $('container'); for(var i = 0; i < imgData.data.length; i++){ var createdBox = document.createElement('div'); createdBox.className = 'box'; oParent.appendChild(createdBox); var imgBox = document.createElement('div'); imgBox.className = 'box_img'; createdBox.appendChild(imgBox); var img = document.createElement('img'); img.src = 'img/' + imgData.data[i].src; imgBox.appendChild(img); } } imgLocation('container', 'box'); }; }; /** 判断何时滚动加载 */ function checkFlag(){ var oParent = $('container'); var oBoxs = getByClass(oParent, 'box'); var lastBoxDistance = oBoxs[oBoxs.length - 1].offsetTop; var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; var viewportHeight = document.documentElement.clientHeight || document.body.clientHeight; if(lastBoxDistance < (scrollTop + viewportHeight)){ return true; } } function imgLocation(parent, childClsName){ var oParent = $(parent); var oBoxs = getByClass(oParent, childClsName); //console.log(oBoxs); var imgWidth = oBoxs[0].offsetWidth; var cols = Math.floor(document.documentElement.clientWidth / imgWidth); oParent.style.cssText = "width:" + imgWidth * cols + "px;margin:0 auto"; /*第一行盒子的高度集合*/ var boxHeightArr = []; for(var i = 0; i < oBoxs.length; i++){ if(i < cols){ boxHeightArr[i] = oBoxs[i].offsetHeight; }else{ //第一行中最小高度的值 var minHeight = Math.min.apply(null, boxHeightArr); console.log(minHeight); var indexOfMinHeight = getMinHeightIndex(boxHeightArr, minHeight); console.log(indexOfMinHeight); oBoxs[i].style.position = 'absolute'; oBoxs[i].style.top = minHeight + 'px'; oBoxs[i].style.left = oBoxs[indexOfMinHeight].offsetLeft + 'px'; //更新高度 boxHeightArr[indexOfMinHeight] = boxHeightArr[indexOfMinHeight] + oBoxs[i].offsetHeight; } } } function getMinHeightIndex(boxHeightArr, minHeight){ for(var height in boxHeightArr){ if(boxHeightArr[height] == minHeight){ return height; } } } function getByClass(parent, childClsName){ var resultArr = [], allElements = parent.getElementsByTagName('*'), i = 0; for(i = 0; i < allElements.length; i++){ if(allElements[i].className == childClsName){ resultArr.push(allElements[i]); } } return resultArr; } function $(id){ return document.getElementById(id); }
不错。。。。
我想问如果数组里面的图片都加载了一次要怎么停止呢,不想无限加载
瀑布流布局
97759 学习 · 736 问题
相似问题