flex换行布局中spacebetween最后一行问题

14次阅读

共计 1575 个字符,预计需要花费 4 分钟才能阅读完成。

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>
正文完
 0