时间:2021-08-22 09:50:22 | 栏目:JavaScript代码 | 点击:次
当我们的网页需要插入很多图片的时候,为了美观,我们可以选择用瀑布流的方法插入图片
首先我们在body里面放入我们需要展示的图片
<div id="box"> <div class="dinwei"> <div class="pic"> <img src="image/1.jpg"> </div> </div> <div class="dinwei"> <div class="pic"> <img src="image/2.jpg"> </div> </div> <div class="dinwei"> <div class="pic"> <img src="image/3.jpg"> </div> </div> <div class="dinwei"> <div class="pic"> <img src="image/4.jpg"> </div> </div> <div class="dinwei"> <div class="pic"> <img src="image/5.jpg"> </div> </div> <div class="dinwei"> <div class="pic"> <img src="image/6.jpg"> </div> </div> <div class="dinwei"> <div class="pic"> <img src="image/7.jpg"> </div> </div> <div class="dinwei"> <div class="pic"> <img src="image/8.jpg"> </div> </div> <div class="dinwei"> <div class="pic"> <img src="image/9.jpg"> </div> </div> </div>
然后设定样式
<style type="text/css"> *{ margin: 0; padding: 0; } .dinwei{ float: left; } .pic{ padding: 5px; border: 1px solid #000000; } img{ margin: 0; padding: 10px; width: 220px; height: auto; } </style>
接下来就是把图片用瀑布流的方式展现的JS
<script type="text/javascript"> window.onload=function(){ var dinwei=document.getElementsByClassName("dinwei"); var windwidth=document.documentElement.clientWidth||document.body.clientWidth; var dinwidth=getStyle(dinwei[0],"width"); var num=Math.floor(windwidth/dinwidth); //计算一行几张图片 //取出高度最小的列 var heightList=[]; for(var i=0;i<dinwei.length;i++){ if(i<num){ heightList[heightList.length]=getStyle(dinwei[i],"height"); }else{ var minHeight=getmin(heightList); var amin=minHeight.value; var index=minHeight.index; var temp=dinwei[i]; temp.style.position="absolute"; temp.style.top=amin+"px"; temp.style.left=index*dinwidth+"px"; heightList[index]=amin+getStyle(temp,"height"); } } } function getmin(arr){ var min=arr[0];[3,3,2,1,5,2] for(var i=1;i<arr.length;i++){ if(arr[i]<min){ min=arr[i]; } } var index=0; for(var j=0;j<arr.length;j++){ if(arr[j]==min){ index=j; break; } } return {value:min,index:index} } function getStyle(obj, attr) { if (obj.currentStyle) { return parseFloat(obj.currentStyle[attr]); } else { return parseFloat(window.getComputedStyle(obj)[attr]); } } </script>