今天做一个简单的瀑布流,相信大家在很多网站都见过类似的瀑布流,一些购物网站里面运用特别多,今天就来制作一下,比较简单
首先是做一个盒子出来,这是设置装瀑布的大盒子,也就是背景.
<div style="width:1200px;height:100px;background:yellow;margin:auto; position:relative;" id="ground">
</div>
基本的做完之后,我们就开始写js代码
<script type="text/javascript">
window.onload = function(){
var ground = document.getElementById('ground');
var count = 36;
var divs = [];
//创建每一个div
for(var i=0;i<count;i++){
var currentView = createDiv(ground);
divs.push(currentView);
}
//给每一个div定位
for(var i=0;i<divs.length;i++){
var curView = divs[i]; //拿到每一个盒子
var index = i - ground.clientWidth/curView.clientWidth ;
if (i==0) { //i为当前的div
curView.style.top = "0px";
curView.style.left = "0px";
}
var preView = divs[index]; //取上头盒子的下标
if (index<0) {
curView.style.top="0px";
}else{
curView.style.top = preView.offsetTop+preView.clientHeight+"px";
}
curView.style.left = i%(ground.clientWidth/curView.clientWidth)*curView.clientWidth +"px";
}
//遍历最后一行取出最高的一个div,赋值给背景的高度
//获取每一个的高度
var hei = [];
for(var i=0;i<ground.clientWidth/curView.clientWidth;i++){
var currenDiv = divs[divs.length-1 - i]; //从数组下标最大值开始取,往前走
var top = currenDiv.offsetTop;
var height = currenDiv.clientHeight;
hei.push(top+height);
}
var maxValue = 0;
for(var i=0;i<hei.length-1;i++){
if (i==0) {
maxValue = hei[i];
}
maxValue = Math.max(maxValue,hei[i+1]);
}
ground.style.height = maxValue+'px';
}
function createDiv(father){
var div1 = document.createElement("div");
div1.style.width = '200px';
//400-500
var height = Math.floor(Math.random()*101+300);
div1.style.height = height+'px';
div1.style.position = "absolute"; //每一个创建的盒子都是绝对定位
div1.style.background = "rgb("+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+")"
father.appendChild(div1);
return div1;
}
</script>
以上就是做瀑布流的方法,比较容易,希望能帮到大家,谢谢

824

被折叠的 条评论
为什么被折叠?



