LoginSignup
5
0

More than 5 years have passed since last update.

jQuery display:noneのエレメントに.width().height()を使う時の注意

Last updated at Posted at 2018-03-20

ボタンで表示/非表示ができるセル状に並んだボックスの、横一列で一番高いheightで高さを揃えようと、何も考えずに以下のように

//高さ調整
var max_height = 0;
_parents.each( function(){
    if ($(this).height() > max_height) {
        max_height = $(this).height();
    }
});
_parents.height(max_height);

とやっていたら、もともとdisplay:inline-blockがCSSで定義されているのに、非表示から表示へ切り替えると
 ■ ■ ■
と並んでいたものが
 ■
 ■
 ■
となってしまう。

ブラウザでエレメントを眺めてみると、非表示のボックスのstyle属性にdisplay:blockが追加されていました。

謎を解明しようとググってみるとjQueryのリファレンスに以下の記述がありました。
Note: Although style and script tags will report a value for .width() or .height() when absolutely positioned and given display:block(抜粋)

てきとーほんやく
「残念ながら、.width().height()は値の報告の際に、styleタグとscriptタグを絶対座標にしてdisplay:blockを付与します」

なんと、破壊的なファンクションだったのね・・・

5
0
0

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
5
0