LoginSignup
1
1

More than 5 years have passed since last update.

要素の高さを揃えるときにUnderscore#reduceが便利

Last updated at Posted at 2016-12-08

複数のDom要素の高さを揃えたいとき、一旦すべての要素走査してMath.maxして最大の高さを取っておく必要があり地味に面倒なのでやり方を模索したメモ。

ありがちな実装例

var maxHeight = 0;
$('.target-item').each(function(element) {
  maxHeight = Math.max(maxHeight, $(this).height());
});
$('.target-item').height(maxHeight);

すっきり版?

ひとまずUnderscore.js の _.reduceをつかうと、比較的スッキリ書けて何やってるか分かりやすい気がします。

// シンプルな例
var max = _.reduce([1,12,23,3,43,9,3], function(memo, val) { return Math.max(memo, val) });
// => 43

var min = _.reduce([1,12,23,3,43,9,3], function(memo, val) { return Math.min(memo, val) });
// => 1

上記の例だとMath.max.apply(Math, [1,12,23,3,43,9,3]);とかしておけよってかんじなんですが、実際にはjQueryで要素など配列で渡して、特定の評価をしたうえで最終的な結果を得ることができます。

var min = _.reduce($('.target-item'), function(memo, element) { return Math.min(memo, $(element).height()) }, 0);
1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1