3

私はこのjQuery関数をまとめました。div.article目的は、画像の高さとドキュメントのベースライングリッド(20ピクセル)のバランスをとるために、内部のすべてのimg要素のマージンを計算することです。ベースライングリッドに一致させるには、すべての画像の高さを20の倍数にする必要があります。そうでない場合、たとえば1つの画像の高さが154ピクセルの場合、関数は画像に6ピクセルのマージンを追加し、ベースラインとのバランスを取ります。グリッドが復元されます。

この関数は正しく機能するので、実際の質問は次のとおりです。私はプログラマーではないので、コードは機能しているのに非常にくだらないのではないかと思います。もしそうなら、コードをどのように改善できるでしょうか。

jQueryコード:

$('div.article img').each(function() {

    // define line height of CSS baseline grid:
    var line_height = 20;

    // capture the height of the img:
    var img_height = $(this).attr('height');

    // divide img height by line height and round up to get the next integer:
    var img_multiply = Math.ceil(img_height / line_height);

    // calculate the img margin needed to balance the height with the baseline grid:
    var img_margin = (img_multiply * line_height) - img_height;

    // if calculated margin < 5 px:
    if (img_margin < 5) {

        // then add another 20 px to avoid too small whitespace:
        img_margin = img_margin + 20;  
    }

    // if img has caption:
    if ($($(this)).next().length) {

        // then apply margin to caption instead of img:
        $($(this)).next().attr('style', "margin-bottom: " + img_margin + "px;");
    } else {

        // apply margin to img:
        $(this).attr('style', "margin-bottom: " + img_margin + "px;");
    }
});

HTMLコードの例、キャプション付きのimg:

<div class="article">
   <!-- [...] -->
    <p class="image">
        <img src="http://example.com/images/123.jpg" width="230" height="154" alt="Image alt text goes here" />
        <small>Image Caption Goes Here</small>
    </p>
   <!-- [...] -->
</div>

HTMLコードの例、キャプションなしのimg:

<div class="article">
    <!-- [...] -->
    <p class="image">
        <img src="http://example.com/images/123.jpg" width="230" height="154" alt="Image alt text goes here" />
    </p>
   <!-- [...] -->
</div>

編集:Russ Camの提案に基づいて洗練されたコード:

var line_height = 20;
var min_margin = 5;
$('div.article img').each(function() {
    var $this = $(this); // prefixed variable name with $ to remind it's a jQuery object
    var img_height = $this.height();
    var img_margin = ((Math.ceil(img_height / line_height)) * line_height) - img_height;
    img_margin = (img_margin < min_margin)? img_margin + line_height : img_margin;
    if ($this.next().length) {      
        $this.next().css({'margin-bottom' : img_margin + 'px'});
    } else {
        $this.css({'margin-bottom' : img_margin + 'px'});
    }
});
4

7 に答える 7

12

私がお勧めできるいくつかの改善

1.ローカル変数$(this)内のキャッシュeach()

$('div.article img').each(function() {

    var $this = $(this); // prefixed variable name with $ 
                         // to remind it's a jQuery object

    // ....

   if ($this.next().length) {

   // ....

   }

});

2.設定する代わりに、コマンドattr('style')を使用しますcss()

3.これを行う必要はありません

$($(this))

jQueryを壊すことはありませんが、jQueryオブジェクトを別のjQueryオブジェクトに渡す必要はありません。

4.$(this).height() または$(this).outerHeight()を使用して、ブラウザで要素の高さを取得します

5. jQuery固有ではありませんが、三項条件演算子を使用してこの値を割り当てることができます

// if calculated margin < 5 px:
if (img_margin < 5) {

    // then add another 20 px to avoid too small whitespace:
    img_margin = img_margin + 20;  
}

になります

// if calculated margin < 5 px then add another 20 px 
// to avoid too small whitespace
img_margin = (img_margin < 5)? img_margin + 20 : img_margin;  

6. Alexがコメントで指摘したように、コードが指示することを単に繰り返すだけの余分なコメントも削除します。これがデバッグスクリプトであっても、私の意見では、読みやすさが低下し、コメントはコードの読み取りに固有ではない詳細を提供するためだけに役立つはずです。

于 2009-11-19T12:31:28.220 に答える
3

コードは問題ありません。あなたはいくつかのマイナーな改善を行うことができます:

  • あちこちで使用しないでください$(this)。早い段階で何かに割り当て、それを使用して、要素を何度も拡張し直さないようにします。
  • $(this).attr('style', "margin-bottom: " + img_margin + "px;");次のように書き直すことができますsomeEl.css('margin-bottom', img_margin + 'px');
于 2009-11-19T12:31:44.403 に答える
2
  1. 画像の高さは要素から取得するのではなく、代わりに$(this).heightを使用します。これは、ブラウザの実際の高さだからです。

とにかくそれはもっと短く書き直すことができます

$('div.article').each(function() {
    var img_margin = 20 - $(this).children('img:first').height() % 20;
    if(img_margin < 5) img_margin += 20;
    if($(this).children('small').length > 0)
         $(this).children('small').attr('style', "margin-bottom: " + img_margin + "px;");
    else
         $(this).children('img').attr('style', "margin-bottom: " + img_margin + "px;");
}
于 2009-11-19T12:34:15.300 に答える
2

何が起こっているかを言うためにすべての行にコメントするべきではありません。コードは何が起こっているかを教えてくれるはずです。(それが本当に本当に奇妙なステートメントでない限り)コメントは、何かが行われている理由
を伝えるために使用されるべきです。

例えば:

// if img has caption:
if ($($(this)).next().length) {

    // then apply margin to caption instead of img:
    $($(this)).next().attr('style', "margin-bottom: " + img_margin + "px;");
} else {

    // apply margin to img:
    $(this).attr('style', "margin-bottom: " + img_margin + "px;");
}

に変更することができます。これは私の目にははるかに読みやすいです。

// if img has caption, apply margin to caption instead
if ($($(this)).next().length) {
    $(this).next().css('margin-bottom', img_margin + 'px;');
} else {
    $(this).css('margin-bottom', img_margin + 'px;');
}
于 2009-11-19T12:39:40.033 に答える
1

私はあなたが落とすことができると思います

$($(this))

に賛成

$(this)
于 2009-11-19T12:31:48.427 に答える
1

高さの計算を高速化および簡素化する方法は次のとおりです。

var img_margin = 20 - ($this.height() % 20);

それは少なくとも少しは役立つはずです。

于 2009-11-19T12:51:11.837 に答える
0

これが私がすることです、コメントでの説明

$(function(){

// put this variable out of the loop since it is never modified
    var line_height = 20;

$('div.article img').each(function() {

    // cache $(this) so you don't have to re-access the DOM each time
    var $this = $(this);


    // capture the height of the img - use built-in height()
    var img_height = $this.height();

    // divide img height by line height and round up to get the next integer:
    var img_multiply = Math.ceil(img_height / line_height);

    // calculate the img margin needed to balance the height with the baseline grid:
    var img_margin = (img_multiply * line_height) - img_height;

    // if calculated margin < 5 px:
    if (img_margin < 5) {

        // then add another 20 px to avoid too small whitespace:
    //use ternary operator for concision
        img_margin += 20;  
    }

    // if img has caption:
    if ($this.next().length) {

        // then apply margin to caption instead of img: - use built-in css() function
        $this.next().css("margin-bottom", img_margin);
    } else {

        // apply margin to img:  - use built-in css() function
        $this.css("margin-bottom", img_margin);
    }
});
});
于 2009-11-19T12:37:22.377 に答える