瀑布流式布局(源码)
瀑布流式布局
[task]<div id="wrap">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>
<div>16</div>
</div>
<script type="text/javascript">// <![CDATA[
document.getElementByClassName = function(className,tag)
{
var tag = tag?tag:"*";
var allTags = document.getElementsByTagName(tag);
var tagNums = allTags.length;
var element = [];
var i=0;
for(n in allTags){
current = allTags.item(n);
if(current!=null){//如果当前元素的class不等于null
if(current.className==className)//找到类名为className的dom元素
{
element[i++]=current;
}
}
}
return element;
}
//该函数获取obj的CSS属性。
function GetCurrentStyle (obj, prop) {
if (obj.currentStyle) {
return obj.currentStyle[prop];
}
else if (window.getComputedStyle) {
propprop = prop.replace (/([A-Z])/g, "-$1");
propprop = prop.toLowerCase ();
return document.defaultView.getComputedStyle (obj,null)[prop];
}
return null;
}
var wrap= document.getElementById("wrap");
var items= document.getElementsByClassName("item");
var i,l,h1,h2,h3;
h1=0;
h2=0;
h3=0;
//i为最大列数,根据容器wrap的宽度和单项的宽度相比得出;
i=Math.floor(parseInt(GetCurrentStyle(wrap,"width"))/parseInt(GetCurrentStyle(items[0],"width")));
//l表示间距。容器宽度-单项宽度*项数=空白宽度,空白宽度/列数-1=每个空白宽度
l=(parseInt(GetCurrentStyle(wrap,"width"))-parseInt(GetCurrentStyle(items[0],"width"))*i)/(i-1);
for(var j=0;j<items.length;j++){
//var h1,h2,h3;
if(j<i){
items[j].style.top="0px";
items[j].style.left= j%i *(l+parseInt(GetCurrentStyle(items[0],"width")))+"px";
if(j%i ==0 ){
h1+=parseInt(GetCurrentStyle(items[j],"height"))+10;//J=0,H1=300
}
else if(j%i==1){
h2+=parseInt(GetCurrentStyle(items[j],"height"))+10;//J=1,H2=250
}
else if(j%i==2){
h3+=parseInt(GetCurrentStyle(items[j],"height"))+10;//J=2,H3=350
}
}
else {
var minheight=Math.min(Math.min(h1,h2),h3);
if( minheight == h1){
items[j].style.top = h1+"px";
items[j].style.left= "0px";
h1+=parseInt(GetCurrentStyle(items[j],"height"))+10;
}
else if(minheight == h2){
items[j].style.top = h2+"px";
items[j].style.left=parseInt(GetCurrentStyle(items[0],"width"))+l+"px";
h2+=parseInt(GetCurrentStyle(items[j],"height"))+10;
}
else if(minheight == h3){
items[j].style.top = h3+"px";
items[j].style.left= (parseInt(GetCurrentStyle(items[0],"width"))+l)*2+"px";
h3+=parseInt(GetCurrentStyle(items[j],"height"))+10;
}
}
}// ]]></script>
[/task]