首頁 > web前端 > js教程 > 主體

Vue木桶佈局的實作方法(附程式碼)

不言
發布: 2018-10-29 14:55:49
轉載
2566 人瀏覽過

這篇文章帶給大家的內容是關於Vue木桶佈局的實作方法(附程式碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

公司最近在重構,使用的是Vue框架。涉及到一個品牌的佈局,因為品牌的字元長度不一致,所以導致每一個的品牌標籤長短不一。多行佈局下就會導致每行的品牌佈局參差不齊,嚴重影響美觀。於是就有了本篇的木桶佈局插件。

木桶佈局的實作是這樣分步驟的:

#1、先對要填放的內容進行排序,篩選出每一行的元素。

2、再對每一行元素進行修整,使其美觀對齊。

分步驟

一、依需求選出每行的元素

#    先取得我們所需的元素、與我們目標容器的寬度。

Vue元件容器:

<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';
    }
})
}
登入後複製

我這邊是採用的平均分配的方式將多餘的寬度平均分配到每一個元素裡。如一行中全部元素佔800px,有8個元素,該行總長為960px。則每行增加的寬度為(960-800)/8=16,每個與元素寬度增加16px;

值得注意的是,js在獲取元素寬度的時候會存在精度問題,所以需要進行預設一個像素進行緩衝。

我的程式碼位址:Github:vue-barrel;npm: vue-barrel

以上是Vue木桶佈局的實作方法(附程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:segmentfault.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!