當我們的網頁需要插入很多圖片的時候,為了美觀,我們可以選擇用瀑布流的方法插入圖片
首先我們在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>
以上就是小編為大家帶來的用瀑布流的方式在網頁上插入圖片的簡單實現方法的全部內容了,希望對大家有所幫助,多多支持~