ゴミ溜め@技術系日常系雑文

主にWeb技術やそのほかつまづいたこととか引っかかって調べたこととかをまとめてます。

はてなダイアリーから引っ越しました。)

jquery.flatheights.jsが上手く動かなかったので修正した。

jQueryでブロック要素の高さを揃えてみるの「jquery.flatheights.js」が素晴らしかったけど、paddingとかborderの値分高さがずれるので修正してみた。

元の内容の、79行目〜の

  /* 高さ揃えの処理本体 */
  var flatHeights = function(set) {
    var maxHeight = 0;
    set.each(function(){
      var height = this.offsetHeight;
      if (height > maxHeight) maxHeight = height;
    });
    set.css('height', maxHeight + 'px');
  };

の部分を

  /* 高さ揃えの処理本体 */
  var flatHeights = function(set) {
    var maxHeight = padding = border = 0;
    set.each(function(){
      var height  = $(this).outerHeight();

      if ( height  > maxHeight ) {
        maxHeight = height; // 最大の高さを当てなおす。
        
        // 過去の栄冠を剥奪。今、CSSクラスに__maxHeightが設定されている要素から、当クラス名を削除する。君が最も大きい存在だったのは過去のことだよ。
        set.removeClass('__maxHeight');
        
        // 君が新しいチャンプだ!該当の要素に__maxHeightクラス名を付加する。
        $( this ).addClass( "__maxHeight" );
      }
    });
    
    // 高さを設定。
    set.each(function() {
      if( !( $(this).hasClass('__maxHeight') ) ) {
        
        // 設定されたpaddingの合計を計算。
        padding =( ( fullstyle( this, 'padding-top'    ) ).replace( /px/, '' ) *1 )
                + ( ( fullstyle( this, 'padding-bottom' ) ).replace( /px/, '' ) *1 );
        
        // 設定されたborderの合計を計算。
        border  = ( ( fullstyle( this, 'border-top-width'    ) ).replace( /px/, '' ) *1 )
                + ( ( fullstyle( this, 'border-bottom-width' ) ).replace( /px/, '' ) *1 );
        
        // 最大の高さから、この要素のborder-widthとpaddingの値を引いた高さを設定する。
        $(this).css('height', maxHeight - ( padding + border ) + 'px');
      }
    });
    
    // 検査用に付加したCSSクラスを削除。
    set.removeClass('__maxHeight');

とした。

途中で使ってる「fullstyle」メソッドは、要素のスタイルを取得するためのもので、中身は下記な感じ。jquery.flatheights.js実行よりも前に記述しておく。

var fullstyle = (function(target, cssProperty){
  if( typeof( cssProperty ) != "undefined" ) {
    if(target.currentStyle){ return target.currentStyle[cssProperty]; }
    else { return ( document.defaultView.getComputedStyle(target, null) ).getPropertyValue(cssProperty); }
  }
  else {
    if(target.currentStyle){ return target.currentStyle; }
    else { return ( document.defaultView.getComputedStyle(target, null) ); }
  }
});

firefoxIE9で見た限り上手く動いてるけど、IE8だとoffsetHeightの返す値の違いのせいか、結局ずれる。〜IE7だと動かない。

まだまだ調整が必要かも。

/* 追記 */
やっぱりheightLine.jsが優秀。class名を付与しないといけないことさえ許容できれば、最良の選択。