Code Depot

【JavaScript】グリットレイアウトの要素の高さを自動で揃える処理

要素が存在しない場合もスキップして、順番が崩れないよう処理しています。

HTML

<ul data-height_adjust='{ "target": ".title, .text", "pc": 4, "tab": 3, "sp": 2 }'>
    <li>
        <h2 class="titile">タイトルが入ります。</h2>
        <p class="text">テキストが入ります。</p>
    </li>
    <li>
        <h2 class="titile">タイトルが入ります。</h2>
    </li>
    <li>
        <h2 class="titile">タイトルが入ります。</h2>
        <p class="text">テキストが入ります。テキストが入ります。テキストが入ります。</p>
    </li>
    <li>
        <h2 class="titile">タイトルが入ります。</h2>
        <p class="text">テキストが入ります。</p>
    </li>
    <li>
        <h2 class="titile">タイトルが入ります。</h2>
        <p class="text">テキストが入ります。テキストが入ります。テキストが入ります。テキストが入ります。</p>
    </li>
    <li>
        <h2 class="titile">タイトルが入ります。</h2>
        <p class="text">テキストが入ります。</p>
    </li>
</ul>

JavaScript

const heightAdjust = (w) => {
	const heightAdjust = document.querySelectorAll('[data-height_adjust]');
	heightAdjust.forEach((e) => {
		const attr = e.getAttribute('data-height_adjust');
		const obj = JSON.parse(attr);

		const targetArray = obj.target.split(','); //配列変換
		const isChildren = (obj.children !== undefined) ? true : false; //子要素
		const pc_col = (obj.pc !== undefined) ? Number(obj.pc) : 0;
		const tab_col = (obj.tab !== undefined) ? Number(obj.tab) : 0;
		const sp_col = (obj.sp !== undefined) ? Number(obj.sp) : 0;

		let col = 0;
		let isSpScroll = false;
		if (w > 1024) {
			col = pc_col;
		} else if (w > 767 && w <= 1023) {
			col = tab_col;
		} else if (w <= 767) {
			col = sp_col;
			const parent = e.parentNode;
			if(parent.hasAttribute('class') && parent.getAttribute('class').match(/c-scroll/)) isSpScroll = true;
		}

		const children = (!isChildren)? Array.from(e.children) : e.querySelectorAll(obj.children);
		if (isSpScroll) col = children.length;

		let height_array = [];
		for (let index = 0; index < targetArray.length; index++) height_array[index] = [];
		
		children.forEach(elm => {
			targetArray.forEach((target,index) => {
				let tempHeight = 0;
				const targetElm = elm.querySelector(target);
				if(targetElm) {
					targetElm.style.height = '';
					tempHeight = targetElm.getBoundingClientRect().height;
				}
				height_array[index] = [...(height_array[index]),tempHeight];
			});
		});

		targetArray.forEach((elm,index) => {
			if(col < 2) return;
			for (let i = 0; i < Math.ceil(children.length / col); i++) {
				let maxHeight = 0;
				for (let n = 0; n < col; n++) {
					let cheldrenCounter = i * col + n;
					if (cheldrenCounter < children.length) { //存在しない子要素を所得しないため
						if (height_array[index][cheldrenCounter] > maxHeight) maxHeight = height_array[index][cheldrenCounter];
					}
				}
				for (let n = 0; n < col; n++) {
					let cheldrenCounter = i * col + n;
					if (cheldrenCounter < children.length) { //存在しない子要素を所得しないため
						let adjustTarget = children[cheldrenCounter];
						adjustTarget = adjustTarget.querySelectorAll(elm);
						if (adjustTarget.length) adjustTarget[0].style.height = `${maxHeight}px`;
					}
				}
			}
		});
	});
}

document.addEventListener("DOMContentLoaded", () => heightAdjust(window.innerWidth), false);
window.addEventListener("load", () => heightAdjust(window.innerWidth), false);
window.addEventListener("resize", () => heightAdjust(window.innerWidth), false);

免責事項

  • 当ブログでは、執筆者の経験に基づいた技術情報や知識を提供していますが、その正確性や普遍性を保証するものではありません。情報は執筆時点のものであり、技術の進展により古くなる可能性があります。これらの情報を利用する際は、自己責任で行ってください。必要に応じて専門家の助言を求めることをお勧めします。
  • 当ブログで提供するプログラムコードは、執筆者の最善の知識に基づいていますが、その正確性や完全性を保証するものではありません。コードの利用や実行により生じた損害や問題については、一切の責任を負いかねます。コードの使用は、自己責任で行ってください。
  • 当サイトで使用しているスクリーンショット画像について、著作権はサイトの権利者に帰属します。掲載に不都合がある場合、お手数ですがお問い合わせフォームよりご連絡ください。
  • 当サイトからリンクよって他のサイトに移動された場合、移動先サイトで提供される情報、サービス等について一切の責任を負いかねますのでご了承ください。
  • 当サイトに掲載された内容によって生じた損害等の一切の責任を負いかねますのでご了承ください。