Web production note

 【更新日 :

【JavaScript】行ごとに特定の要素の高さを揃える

Category:
JavaScript

JavaScriptで行ごとに特定の要素の高さを揃える機能を実装したサンプルです。

高さ揃え系はflexboxやgridの登場で利用頻度が激減しましたが
スライダー内の一部を揃えるなど、ややトリッキーな場では活躍してくれると思います。

codepen

See the Pen Align the height of each row (Vanilla JS) by web_nak (@web_walking_nak) on CodePen.

JavaScript

//要素高さ調整関数
const listHeight = (setOptions) => {
  const defaultOptions = {
    targets: null,  //対象リスト
    parent: null,  //検索対象にする親要素
    column: 1,  //カラム数
  };

  //設定をマージ
  const options = Object.assign({}, defaultOptions, setOptions);

  //ターゲットが存在しない場合は終了
  let targets = options.targets;
  if(targets === null) {
    return;
  }

  //親グループが指定されているかチェック
  const parent = options.parent;
  if(parent !== null) {
    targets = parent.querySelectorAll(targets);
  } else {
    targets = document.querySelectorAll(targets);
  }

  //要素の高さをリセット
  targets.forEach((target) => {
    target.style.height = '';
  });

  //設定された列の数が1以下だった場合は処理を停止
  const column = options.column;
  if(column <= 1) {
    return;
  }

  //行の高さの配列
  let lineHeightArray = [];
  //行ごとの要素の高さを取得
  targets.forEach((target,i) => {
    const height = target.offsetHeight;
    //行番号を取得
    const arrayIndex = Math.floor(i / column);
    if (lineHeightArray.length <= arrayIndex || lineHeightArray[arrayIndex] < height) {
        lineHeightArray[arrayIndex] = height;
    }
  });

  //要素の高さを変更
  targets.forEach((target,i) => {
    target.style.height = lineHeightArray[Math.floor(i / column)] + 'px';
  });
}

関数の呼び出し

任意の場所で以下を実行し関数を呼び出してください。

listHeight({
  targets: '.hoge',  //対象リスト(class名)
  parent: element,  //検索対象にする親要素(任意)
  column: 4,  //カラム数
});