瀑布流效果js实现

瀑布流js实现

 1  // 页面尺寸改变时实时触发
 2 window.onresize = function() {
 3     //重新定义瀑布流
 4     waterFall();
 5 };
 6 
 7 //初始化
 8 window.onload = function(){
 9     console.log("开始瀑布流")
10     //实现瀑布流
11     waterFall();
12 
13 }
14 
15 function waterFall(){
16     //1.求出列数
17     var box = $(".item");     
18     var boxWidth = box.outerWidth(); //当前图片的宽度    不用width是因为width会使图片紧挨着左右没有间隙,而outerWidth会在图片宽度基础上加上padding以致每张图片左右有一定的间隙20     var screenWidth = $(window).width();  //整个屏幕的宽度
21     var cols = parseInt(screenWidth/boxWidth);  //列数23     //2.创建数组
24     var heightArr = [];
25     //3.图片遍历循环,除第一排不需要定位,取高度值 其他排  定位处理
26     $.each(box,function(index,item){
27         //取出图片的高度29         var boxHeight = $(item).outerHeight();
30         if(index < cols){    //第一排,取高度值32             heightArr[index] = boxHeight;
33         }else{
34             //最小图片的高度
35             //数组中最小的值
36             var minBoxHeight = Math.min(...heightArr);   //第一列图片高度值存放在数组中heightArr,找出最小值
37             //最小的索引
38             var minBoxIndex = $.inArray(minBoxHeight,heightArr);   //遍历数组heightArr中查找minBoxHeight这个最小值,返回下标。
39             $(item).css({
40                 position:'absolute',
41                 left:minBoxIndex*boxWidth+'px',
42                 top:minBoxHeight+'px'
43             });
44             //高度追加
45             heightArr[minBoxIndex] += boxHeight;
46         }
47     })
48 }

猜你喜欢

转载自www.cnblogs.com/cccaroline/p/13377803.html