在图片瀑布流中,第二排的第一张图片要放到第一排高度最小的图片下面,于是在for循环中定义,当图片数量大于图片列数的时候,得到minHeight。假设每排有7张图片,但第9张图片是高度最小的,得到的minHeight不是第九张图片吗?为什么代码中的minHeight得到的是第一排的7张图中高度最小的一张呢?
function imgLocation(parent,content){
var cparent =document.getElementById(parent);
var ccontent = getChildElement(cparent,content);
var imgWidth = ccontent[0].offsetWidth;
var cols = Math.floor(document.documentElement.clientWidth / imgWidth);
cparent.style.cssText = "width:"+imgWidth*cols+"px;margin:0 auto";
var BoxHeightArr=[];
for(var i=0;i<ccontent.length;i++){
if(i<cols){
BoxHeightArr[i] = ccontent[i].offsetHeight;
}else{
var minHeight = Math.min.apply(null,BoxHeightArr);
var minLocation = getMinHeightLocation(BoxHeightArr,minHeight);
ccontent[i].style.position = "absolute";
ccontent[i].style.top = minHeight+"px";
ccontent[i].style.left = ccontent[minLocation].offsetLeft+"px";
BoxHeightArr[minLocation] = BoxHeightArr[minLocation]+ccontent[i].offsetHeight;
}
}
}
天蓬老师2017-04-10 17:06:39
比如每排7张,也就是说容器中有7列 clos = 7
可以把这7列想象为7个容器
那个 boxHeightArr 就是存的这七个容器的高度
当 i < cols 时:
BoxHeightArr[i] = ccontent[i].offsetHeight; 因为开始时容器里没有图片,高度都是0,所以依次放入就好了,放入后高度都等于图片的高度。
当前7张放入后也就是 i >= cols 时:
因为所有容器中都有了图片,他们的高度也就因此不一样了,所以要找到最短的那个容器,然后把新的图片放到最短的容器里,给最短的容器的高度加上新放入的图片的高度
过程就是这样
minHeight不是图片的最小高度,是容器里高度最小的容器的高度
minLocation是最小的容器的位置