web関連

【javascript】(インラインスタイルの時の)コンテンツの高さを一番高い要素に整える

インラインスタイルシートで高さを指定されている時にjavascriptでうまく高さの上書きができなかったときの備忘録

以下は前回のjqueryとインラインスタイルシートじゃない時の備忘録

インラインスタイルシートの高さを一番高い高さに上書きする方法

インラインスタイルで書かれたhtmlコード

<div class="contents">
	<div class="content" style="height: 211px;">211px</div>
	<div class="content" style="height: 423px;">423px</div>
	<div class="content" style="height: 333px;">333px</div>
</div>
こいつらを一番高い高さに高さを合わせたい

javascriptの.style.cssTextを使ってインラインスタイルを上書きする

.style.cssTextを使うとインラインスタイルシートを上書きできる

<script>
var maxHeight = 0;
const lists = document.querySelectorAll('.content');
var inlineCss ='';// インラインのstyle属性を上書きするための変数
for (var i = 0; i < lists.length; i++) {
	// 変数に入っている高さを上回ったら上書きする
	if (lists[i].clientHeight > maxHeight) {
		inlineCss = lists[i].style.cssText;// 「height: 423px;」が入る
		maxHeight = lists[i].clientHeight;
	}
};
for (var i = 0; i < lists.length; i++) {
	// ↓インラインのstyle属性を上書き
	lists[i].style.cssText = inlineCss + "background-color: yellow;";
};
</script>
いるかわからんけどデモ

inlineCss + "background-color: yellow;"で他のプロパティも一緒に指定できる(メモ)
それに!importantをつけたりできる

参考

JavaScriptでの要素のスタイル操作で !important を使う方法

.cssTextプロパティの存在初めて知ったわ
こんなのあるんすね

Leave a Comment

入力エリアすべてが必須項目です。メールアドレスが公開されることはありません。

内容をご確認の上、送信してください。