公司最近在重构,使用的是Vue框架。涉及到一个品牌的布局,由于品牌的字符长度不一致,因此致使每个的品牌标签长短不一。多行布局下就会致使每行的品牌布局良莠不齐,严重影响美观。因而就有了本篇的木桶布局插件。vue
首先获取咱们须要的元素、和咱们目标容器的宽度。git
Vue组件容器:github
<template> <div ref="barrel"> <slot></slot> </div> </template>
this.barrelBox = this.$refs.barrel; this.barrelWidth = this.barrelBox.offsetWidth;
ps:对于元素的宽度获取的时候咱们须要对盒模型进行区分。
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); } })
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'; } })
}npm
我这边是采用的平均分配的方式将多余的宽度平均分配到每个元素里。如一行中所有元素占800px,有8个元素,该行总长为960px。则每行增长的宽度为(960-800)/8=16,每一个与元素宽度增长16px;
值得注意的是,js在获取元素宽度的时候会存在精度问题,因此须要进行预设一个像素进行缓冲。框架
Github:vue-barrel布局
npm: vue-barrelthis