????公司最近在重構(gòu),使用的是Vue框架。涉及到一個(gè)品牌的布局,因?yàn)槠放频淖址L(zhǎng)度不一致,所以導(dǎo)致每一個(gè)的品牌標(biāo)簽長(zhǎng)短不一。多行布局下就會(huì)導(dǎo)致每行的品牌布局參差不齊,嚴(yán)重影響美觀。于是就有了本篇的木桶布局插件。
木桶布局的實(shí)現(xiàn)是這樣分步驟的:
- 首先對(duì)要填放的內(nèi)容進(jìn)行排序,篩選出每一行的元素。
- 再對(duì)每一行元素進(jìn)行修整,使其美觀對(duì)齊。
分步驟
一、根據(jù)需要選出每行的元素
????首先獲取我們需要的元素、和我們目標(biāo)容器的寬度。
Vue組件容器:
<template>
<div ref="barrel">
<slot></slot>
</div>
</template>
二、再者我們需要獲取容器和容器寬度
this.barrelBox = this.$refs.barrel;
this.barrelWidth = this.barrelBox.offsetWidth;
三、接著循環(huán)我們的元素,根據(jù)不同的元素的寬度進(jìn)行分組。
ps:對(duì)于元素的寬度獲取的時(shí)候我們需要對(duì)盒模型進(jìn)行區(qū)分。
Array.prototype.forEach.call(items, (item) => {
paddingRight = 0;
paddingLeft = 0;
marginLeft = parseInt(window.getComputedStyle(item, "").getPropertyValue('margin-left'));
marginRight = parseInt(window.getComputedStyle(item, "").getPropertyValue('margin-right'));
let boxSizing = window.getComputedStyle(item, "").getPropertyValue('box-sizing');
if (boxSizing !== 'border-box') {
paddingRight = parseInt(window.getComputedStyle(item, "").getPropertyValue('padding-right'));
paddingLeft = parseInt(window.getComputedStyle(item, "").getPropertyValue('padding-left'));
}
widths = item.offsetWidth + marginLeft + marginRight + 1;
item.realWidth = item.offsetWidth - paddingLeft - paddingRight + 1;
let tempWidth = rowWidth + widths;
if (tempWidth > barrelWidth) {
dealWidth(rowList, rowWidth, barrelWidth);
rowList = [item];
rowWidth = widths;
} else {
rowWidth = tempWidth;
rowList.push(item);
}
})
四、接著是對(duì)每一組的元素進(jìn)行合理分配。
const dealWidth = (items, width, maxWidth) => {
let remain = maxWidth - width;
let num = items.length;
let remains = remain % num;
let residue = Math.floor(remain / num);
items.forEach((item, index) => {
if (index === num - 1) {
item.style.width = item.realWidth + residue + remains + 'px';
} else {
item.style.width = item.realWidth + residue + 'px';
}
})
}
????我這邊是采用的平均分配的方式將多余的寬度平均分配到每一個(gè)元素里。如一行中全部元素占800px,有8個(gè)元素,該行總長(zhǎng)為960px。則每行增加的寬度為(960-800)/8=16,每個(gè)與元素寬度增加16px;
????值得注意的是,js在獲取元素寬度的時(shí)候會(huì)存在精度問(wèn)題,所以需要進(jìn)行預(yù)設(shè)一個(gè)像素進(jìn)行緩沖。
以下是我的代碼地址
Github:vue-barrel
npm: vue-barrel