Vue木桶布局插件

    公司最近在重构,使用的是Vue框架。涉及到一个品牌的布局,由于品牌的字符长度不一致,因此致使每个的品牌标签长短不一。多行布局下就会致使每行的品牌布局良莠不齐,严重影响美观。因而就有了本篇的木桶布局插件。vue

木桶布局的实现是这样分步骤的:
  1. 首先对要填放的内容进行排序,筛选出每一行的元素。
  2. 再对每一行元素进行修整,使其美观对齐。

分步骤

1、根据须要选出每行的元素

    首先获取咱们须要的元素、和咱们目标容器的宽度。git

Vue组件容器:github

<template>
  <div ref="barrel">

      <slot></slot>

  </div>
</template>
2、再者咱们须要获取容器和容器宽度
this.barrelBox = this.$refs.barrel;

this.barrelWidth = this.barrelBox.offsetWidth;
3、接着循环咱们的元素,根据不一样的元素的宽度进行分组。
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);

            }

        })
4、接着是对每一组的元素进行合理分配。
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

相关文章
相关标签/搜索