1.遇到的问题
在数量不固定,每一行又须要依据父级宽度动态变化,且在一行中又要均匀间距时,会呈现如下状况
(例1)
(例2)
2.解决办法
(1)设置为flex-start,动静计算每一个子元素的左边距
(2)在父级宽度变动后,算出每一行子元素的个数,再减去子级总数与行个数取模后的数,失去最终须要补齐的个数
第一种办法略微简单点,这里不再具体阐明,次要说第二种办法。
这里用到了ResizeObserver
办法,能够察看某个元素高宽度及地位的变动。
const resizeObserver = new ResizeObserver(this.resizeChangeWH);resizeObserver.observe(this.$el);
resizeChangeWH(entries){ const childNodes = this.$el.childNodes; let row = 0,beforeNode=null; for(let i=0;i<childNodes.length;i++){ let node = childNodes[i]; if(!beforeNode){ beforeNode = node; continue; } if(node.offsetTop !== beforeNode.offsetTop){ row = i; break; } } this.repair = row>1?row - this.boxItemNum%row:0; }
当父级元素变动后,获得所有子元素,遍历子元素时发现某一个子元素的offsetTop与之前不一样,则证实此地位开始换行,即而得出每一行的个数
运行后的成果如下:
附Vue源码:
<template> <div class="box-content"> <div class="box-item main" v-for="item in boxItemNum" :key="'main'+item"/> <div class="box-item repair" v-for="item in repair" :key="'repair'+item"></div> </div></template><script>export default { data(){ return { boxItemNum:11, repair: 0, } }, mounted(){ const resizeObserver = new ResizeObserver(this.resizeChangeWH); resizeObserver.observe(this.$el); }, methods:{ resizeChangeWH(entries){ const childNodes = this.$el.childNodes; let row = 0,beforeNode=null; for(let i=0;i<childNodes.length;i++){ let node = childNodes[i]; if(!beforeNode){ beforeNode = node; continue; } if(node.offsetTop !== beforeNode.offsetTop){ row = i; break; } } this.repair = row>1?row - this.boxItemNum%row:0; } }}</script><style lang="scss" scoped> .box-content{ width: 100%; display: flex; justify-content: space-between; flex-flow: wrap; .box-item{ width: 256px; height: 144px; margin: 15px; &.main{ background-color: #ff0000; } &.repair{ background-color: #00ff00; } }}</style>