一个不错的瀑布流
代码非原创,但是有一个小问题,就是当有另外一个div包住ul时,div的高度只会是第一排li的高度。
为此修改了N遍css都不行。最后只好在js内强制设定div的高度了。
document.getElementById("sss").style.height=Math.max.apply('',aH)+10+"px"; //该div的id为sss
| <script type="text/javascript"> | |
| window.onload=function() | |
| { | |
| waterfall($$('wrap')); | |
| // var height = document.getElementById("li").style.height; | |
| // document.getElementById("sss").style.height = height; | |
| }; | |
| window.onresize=function(){waterfall($$('wrap'));}; | |
| var $$=function(id){return document.getElementById(id) || id}; | |
| function getStyle(obj,attr) | |
| { | |
| return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,false)[attr]; | |
| } | |
| //获取最小高度的Li的索引值 | |
| function getTheMini(arr,MinH) | |
| { | |
| for(k in arr) | |
| { | |
| if(arr[k]==MinH) | |
| { | |
| return k; | |
| } | |
| } | |
| } | |
| function waterfall(obj) | |
| { | |
| var aH=[]; | |
| var aObj=obj.getElementsByTagName('li'); | |
| var oBoxW=aObj[0].offsetWidth+10, | |
| oBoxMinH=aObj[0].offsetHeight, | |
| oBoxH; | |
| var nNum=2; | |
| //var nNum=document.documentElement.offsetWidth/oBoxW | 0; | |
| obj.style.width=nNum*oBoxW+"px"; | |
| for(var i=0;i<aObj.length;i++) | |
| { | |
| oBoxH=aObj[i].offsetHeight+10; | |
| if(nNum>i) | |
| { | |
| aH[i]=oBoxH; | |
| aObj[i].style.position=""; | |
| } | |
| else | |
| { | |
| minH=Math.min.apply('',aH);//获取数组中的最小值 | |
| minKey=getTheMini(aH,minH); | |
| aH[minKey] +=oBoxH; | |
| aObj[i].style.position="absolute"; | |
| aObj[i].style.top=minH+10+"px"; | |
| aObj[i].style.left=(minKey*oBoxW)+"px"; | |
| document.getElementById("sss").style.height=Math.max.apply('',aH)+10; | |
| } | |
| // var obS = ob.getElementsByTagName('li'); | |
| // var maxH = 0; | |
| // for(int i=0;i<=obS.length;i++){ | |
| // if(obS[i].offsetWidth > maxH){maxH=obS[i].offsetWidth;} | |
| // } | |
| // document.getElementById("sss").style.height=maxH; | |
| } | |
| } | |
| </script> |
| <style type="text/css"> | |
| *{ padding:0; margin:0; list-style:none; font-size:12px; font-family:"微软雅黑";} | |
| .sss {width: 420; background-color: black; color: white; overflow-x:hidden;word-wrap:break-word ; } | |
| .wrap{ position:relative; zoom:1; margin:0 auto; } | |
| .wrap li{ width:120px; margin:5px; border:1px solid #CCC;float:left;word-break:break-all;display:inline-block;} | |
| .wrap li .title{ margin:8px; padding:6px; background:#EEE;} | |
| .wrap li .content{ margin:8px; padding:6px; color:#AAA;} | |
| .wrap li .footer{ margin:8px; padding:6px; color:#AAA;text-align:center; } | |
| </style> |

浙公网安备 33010602011771号