Js实现瀑布流效果
通过JavaScript实现瀑布流效果,实现不同大小的图片有序展示
效果图:
核心:
1.将图片宽度固定,用浏览器窗口大小除以每个图片的宽度,求出要分成的列数
2.将每个图片定位
3.每次找到最小高度的列,将图片加到该列后
HTML部分以及CSS样式
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title><style>* {margin: 0px;padding: 0px;}div {width: 150px;position: absolute;border: 1px solid;}img {display: inline-block;width: 150px;}#wrap {position: relative;width: 100%;}</style></head><body><div>瀑布流<img src="./img/1.jpg" alt=""></div><div>瀑布流<img src="./img/2.jpg" alt=""></div><div>瀑布流<img src="./img/3.jpg" alt=""></div><div>瀑布流<img src="./img/4.jpg" alt=""></div><div>瀑布流<img src="./img/5.jpg" alt=""></div><div>瀑布流<img src="./img/6.jpg" alt=""></div><div>瀑布流<img src="./img/7.jpg" alt=""></div><div>瀑布流<img src="./img/8.jpg" alt=""></div><div>瀑布流<img src="./img/9.jpg" alt=""></div><div>瀑布流<img src="./img/10.jpg" alt=""></div><div>瀑布流<img src="./img/11.jpg" alt=""></div><div>瀑布流<img src="./img/12.jpg" alt=""></div><div>瀑布流<img src="./img/13.jpg" alt=""></div><div>瀑布流<img src="./img/14.jpg" alt=""></div><div>瀑布流<img src="./img/15.jpg" alt=""></div><div>瀑布流<img src="./img/16.jpg" alt=""></div><div>瀑布流<img src="./img/17.jpg" alt=""></div><div>瀑布流<img src="./img/18.jpg" alt=""></div><div>瀑布流<img src="./img/19.jpg" alt=""></div><div>瀑布流<img src="./img/20.jpg" alt=""></div><div>瀑布流<img src="./img/1.jpg" alt=""></div></body>
</html>
js代码
<script>var div = document.getElementsByTagName("div");//因为图片较多,在加载时,就加载图片window.onload = function(){Full();}//当窗口大小改变时,重新分列并排序window.onresize = function(){Full();}//瀑布流函数function Full(){//求分几列var pw = document.documentElement.offsetWidth; //页面宽度var dw = div[0].offsetWidth; //每个div宽度var cols = Math.floor(pw/dw);//缝隙数等于列数加1,例如6行有7个缝隙var white = (pw - dw * cols)/(cols + 1);//每一列定位var t = 10;var arr = []; for(var i = 0;i<cols;i++){var pos = {//计算每个div的坐标(开始让每个top取一个固定值)//横坐标每次不变,只有top变/* div[0] left: whitediv[1] left: white*2 + dwdiv[2] left: white*3 + dw*2*/x:Math.floor((i+1)*white+dw*i),y:t }arr.push(pos); //将坐标存入数组 }console.log(arr);//每次找高度最小的一列for(var j = 0;j<div.length;j++){var index = getMinTop(arr);div[j].style.left = arr[index].x + "px";div[j].style.top = arr[index].y + "px";arr[index].y += div[j].offsetHeight + t;console.log("arr[index]",arr[index]);}}//求每次最小高度的列function getMinTop(arr){var minT = arr[0].y;var index = 0;for(var k = 0;k<arr.length;k++){if(arr[k].y < minT){minT = arr[k].y;index = k;}}return index;}
</script>