前端页面--瀑布流布局的实现 青旅半醒 2021-07-26 16:51 597阅读 0赞 前端页面--瀑布流布局的实现: html:差不多就是这种结构,source-item为瀑布流盒子 <div class="source-content"> <div class="source-item"></div> <div class="source-item"></div> <div class="source-item"></div> <div class="source-item"></div> <div class="source-item"></div> <div class="source-item"></div> <div class="source-item"></div> <div class="source-item"></div> </div> css:加上定位样式 .source-content{ position: relative; } .source-item{ width: 20%; padding: 8px; position: absolute; /* 布局transition效果 */ /*transition: all .4s;*/ } js:js代码部分 <script> var colCount; //定义列数 var colHeightArry= [] //定义列高度数组 var imgWidth = $('.source-content .source-item').outerWidth(true) //单张图片的宽度 colCount = parseInt($('.source-content').width()/imgWidth) //计算出列数 for(var i = 0 ; i < colCount; i ++){ colHeightArry[i] = 0 } //[0,0,0] $('.source-content .source-item').on('load',function(){ var minValue = colHeightArry[0] //定义最小的高度 var minIndex = 0 //定义最小高度的下标 for(var i = 0 ; i < colCount; i ++){ if(colHeightArry[i] < minValue){ //如果最小高度组数中的值小于最小值 minValue = colHeightArry[i] //那么认为最小高度数组中的值是真正的最小值 minIndex = i //最小下标为当前下标 } } $(this).css({ left: minIndex * imgWidth, top: minValue }) colHeightArry[minIndex] += $(this).outerHeight(true) }) //当窗口大小重置之后,重新执行 $(window).on('resize',function(){ reset() }) //当窗口加载完毕,执行瀑布流 $(window).on('load',function(){ reset() }) //定义reset函数 function reset(){ var colHeightArry= [] colCount = parseInt($('.source-content').width()/imgWidth) for(var i = 0 ; i < colCount; i ++){ colHeightArry[i] = 0 } $('.source-content .source-item').each(function(){ var minValue = colHeightArry[0] var minIndex = 0 for(var i = 0 ; i < colCount; i ++){ if(colHeightArry[i] < minValue){ minValue = colHeightArry[i] minIndex = i } } $(this).css({ left: minIndex * imgWidth, top: minValue }) colHeightArry[minIndex] += $(this).outerHeight(true) }) var imgBoxNum = $(".source-content .source-item").length-1; var imgHeight = $(".source-content .source-item").eq(imgBoxNum).height(); var imgTop= $(".source-content .source-item").eq(imgBoxNum).position().top; var outBoxHeight = imgHeight+imgTop+"px"; $(".source-content").css("height",outBoxHeight); } </script> 添加滚动到底部加载数据: $(window).on("resize scroll",function(){ var windowHeight = $(window).height();//当前窗口的高度 var scrollTop = $(window).scrollTop();//当前滚动条从上往下滚动的距离 var docHeight = $(document).height(); //当前文档的高度 /*console.log(scrollTop, windowHeight, docHeight);*/ //当 滚动条距底部的距离 + 滚动条滚动的距离 >= 文档的高度 - 窗口的高度 //换句话说:(滚动条滚动的距离 + 窗口的高度 = 文档的高度) 这个是基本的公式 if (scrollTop + windowHeight >= docHeight) { console.log("===加载更多数据,往source-content里面添加数据==="); var html = $(".source-content").html(); $(".source-content").append(html); reset(); } });
还没有评论,来说两句吧...