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

移动端常见布局方案

时间:2023-04-05 00:24:31 HTML5

.slide-page-all{visibility:hidden;position:absolute;top:0;left:0;right:0;.virtual-content{font-size:20px;line-height:1.5;}}场景一:子页面自动切分需要根据页面容器的大小自动填充对话内容。当屏幕太大而无法只显示一个对话时,缩小字体大小以适合容器大小。实现原理是用一个隐藏的内容区域元素作为虚拟容器来衡量内容渲染所需的实际空间,然后通过得到的实际空间计算分页。父组件:虚拟元素组件:.slide-page-all{visibility:hidden;position:absolute;top:0;left:0;right:0;.virtual-content{font-size:20px;line-height:1.5;}}注意:为了保证虚拟容器先于实际目标容器加载,可以将虚拟容器作为与目标容器同级的子组件分页计算//添加索引constaddIndexToValue=arr=>{returnarr.map((v,i)=>{return{index:i,height:v};});};/**分页算法【key】*arr:每条内容实际高度的集合*max:目标容器的最大高度*/constgetPages=(arr,max)=>{if(max<=0){return[];}常量结果=[];constdata=addIndexToValue(arr);让前=0;让tmp=[];for(leti=0,len=data.length;i=max){if(tmp.length>0){result.push(tmp);tmp=[{...(data[i]||{}),currentIndex:0}];pre=data[i].height;if(i===data.length-1){result.push(tmp);}}else{result.push([{...(data[i]||{}),currentIndex:0}]);tmp=[];}}else{tmp.push({...(data[i]||{}),currentIndex:tmp.length});pre=pre+data[i].height;if(i===data.length-1){恢复lt.push(tmp);}}}returnresult;};//buffervalue15constOFFSET=15;//实际在页面中的应用exportconstgetComputedNode=index=>{constwrap=document.getElementById('view-container');如果(!wrap){返回[];}constparent=document.getElementById(`nodes-parent-${index}`);constwrapHeight=wrap.clientHeight;constchildren=Array.from(parent.children);constarr=[];children.reduce((pre,node)=>{constheight=node.clientHeight;pre.push(height);returnpre;},arr);constresult=getPages(arr,wrapHeight-OFFSET);返回结果;};字体缩小判断//font-sizepublicgetResizeStyle(sliderIndex,pIndex){constswiperPages=this.list[sliderIndex];if(swiperPages.length===1){//只有一句话,const{height}=this.list[sliderIndex][pIndex];//height:自适应时的预设高度constparentHeight=document.getElementById('view-container').clientHeight;//parentHeight:实际父容器高度constwordEl=document.querySelector('.virtual-content.word');if(!wordEl){//当元素未呈现时返回'';}constfontSizeStr=window.getComputedStyle(wordEl)['字体大小']||'';constfontSize=parseFloat(fontSizeStr);//当预设高度大于父容器的实际高度时,字体应该缩小以适应显示)}px`;}返回'';}else{返回'';}}扩容后,如果遇到需要适配的东西,可以用虚元测量,然后计算适配场景2:每排三张卡片,要求连续3张,少于3张的排列在从左到右的顺序。实现原理每行固定三个元素,每个元素的高度固定,水平和垂直间距固定,宽度自适应。为了很好的支持justify-content:space-between,需要处理sum%3为2的情况:在数据的顶部插入一个空元素。内容{显示:flex;弹性包装:包装;justify-content:space-between;}场景三:内容靠左,整体居中要求将不同长度段落中的所有段落内容显示在左侧,段落外的容器显示在中间页。实现原理布局分为三个层次:文本段落、文本段落容器、章节容器为了实现水平方向的文本内容达到上限才换行,文本段落容器采用display:inline-block,所以水平方向自动换行后的文字内容是满的。文本段落容器text-align:left实现左对齐。pcontainer{显示:内联块;text-align:left}章节容器实现内容居中对齐。chapter{display:flex;justify-content:center;}参考资料:https://zhuanlan.zhihu.com/p/...

最新推荐
猜你喜欢