当前位置: 首页 > Web前端 > HTML

简单实现一张不规则大小的卡片自动填充布局

时间:2023-04-02 22:22:41 HTML

要实现这样的效果,flex或者float是单靠CSS无法实现的。要实现这样的效果,我们需要使用绝对定位,然后使用JavaScript。计算每张卡片的left和top值这里有一个demo先创建一个卡片容器

addstyle我们假设卡片宽度固定,默认100px随机生成100组卡片数据constContainer=document.getElementById("main");让totalWidth=Container.getBoundingClientRect().widthconstDefaultWidth=100;functiongetRandom(){returnMath.ceil(((Math.random())*50))+100}functionColor(){letr=Math.ceil(Math.random()*255);让g=Math.ceil(数学.r安多姆()*255);让b=数学。ceil(Math.random()*255);返回'??rgba('+r+','+g+','+b+',0.8)';}让数据=[];for(leti=0;i<100;i++){data.push({height:getRandom(),background:Color(),})}然后遍历这100组数据生成卡片添加到When第一次遍历容器,保存每一列的高度、行列信息,然后在第一行填满后,剩下的行从最短没有列的卡片开始填充剩下的卡片,从而填满剩下的牌顺理成章。代码逻辑如下/*行列信息*/letrowColInfos=[];让currentCol=0;让currentRow=0;//对每行信息进行一次排序letisSort=false;//检查当前行是否已满letmark=0;constfrag=document.createDocumentFragment();for(letdofdata){letdiv=document.createElement("div");div.style.width=DefaultWidth+"px";div.style.height=d.height+"px";div.style.backgroundColor=d.background;frag.append(div);//第一行,记录当前列的初始数据if(currentRow===0){heightData[currentCol]={height:d.height,row:currentRow,col:currentCol,};div.style.left=DefaultWidth*currentCol+"px";div.style.top=0;如果(DefaultWidth*(currentCol+1)+DefaultWidth>=totalWidth){currentRow++;}否则currentCol++;}else{//当前每一列的高度,从低到高排序if(!isSort){heightData.sort((d1,d2)=>d1.height-d2.height);排序=真;}for(letinfoofheightData){//获取当前行的数据信息,给当前卡片的位置if(info.row+1===currentRow){div.style.left=info.col*DefaultWidth+"px";div.style.top=info.height+"px";info.height+=d.height;标记++;信息行++;休息;}}//这一行填充完毕,进行下一轮填充if(mark===heightData.length){mark=0;isSort=false;当前行++;}}}内容ner.appendChild(片段);这里总结一个定宽卡片自动填充的简单实现。如果需要扩展,比如1.添加过渡效果,第一次遍历需要插入到元素中,第二次遍历改变元素位置2.不同宽度和不同高度的适配太复杂了并且需要使用更高级的算法。一般不使用。如果有更好的方法也可以留言交流