2

動的に取得する一連の画像があります。最大高さを適用している各画像に、サイズ変更の目的でこれを使用します。

jqueryのサイズ変更機能があります:

//写真のサイズを変更します

function resizeMyImg(objct, containerWidth, containerHeight) {
   var width   = $(objct).width();   // I try alerting here and get a 0 answer
   if (width < containerWidth) {
       var percentageToAdd = ((100 * width) / containerWidth) + 100;
       $(objct).css({ maxHeight: percentageToAdd + "%" });
   }
}

そして、私はこのサイズ変更機能を私の画像に適用しようとしています:

$(document).ready(function () { 
    $(".photoAlbum").find("img").each(function () {
        var myImage2 = $(this);
        myImage2.load(function () {
            alert(myImage2.height());   // I try alerting here and also get a 0 answer
            resizeMyImg(myImage2, 240, 240);
        });
    });
});

これは私のページで使用しているhtmlです。お役に立てば幸いです。

<div style="padding-top: 0px;" id="photosHere">

                    <div class="photoAlbum">

                        <img alt="" src="/Uploads/553290_471992686161625_498413822_n867.jpg" style="max-height: 100%;">

                    </div>

                    <div class="photoAlbum">

                        <img alt="" src="/Uploads/484524_430827793626240_991120671_n575.jpg" style="max-height: 100%;">

                    </div>

                    <div class="photoAlbum">

                        <img alt="" src="/Uploads/553290_471992686161625_498413822_n717.jpg" style="max-height: 100%;">

                    </div>

                    <div class="photoAlbum">

                        <img alt="" src="/Uploads/me993.jpg" style="max-height: 100%;">

                    </div>

                    <div class="photoAlbum">

                        <img alt="" src="/Uploads/me759.jpg" style="max-height: 100%;">

                    </div>

                </div>

私の問題は、画像の幅を取得できないことです。実際の幅ではなく、常に0を取得します。ただし、firebugを使用して画像をテストすると、正しい幅が得られます。

注意:正しい答えが得られることもありますが、更新して再び0を取得します。何か提案をお願いします?? 私がこれに何時間も費やしたのはイライラします。

4

2 に答える 2

3

今日、私は jQuery プラグインを作成していましたが、同じ問題が発生したため、代わりに DOM 要素を参照することになりました。試す

$(this)[0].heightそれ以外のmyImage2.height()

$(this)[0].widthの代わりにmyImage2.width()

于 2012-12-22T03:53:11.317 に答える
0

正しい幅はfirebugのいじりによるものである可能性があり、リフレッシュするとすべてのいじりが解消されると思います。

試しましたか:

 alert(myImage2.outerHeight());

2番目に表示されたコードで

var width = $(objct).outerWidth

あなたの最初のコードで?( http://api.jquery.com/outerWidth/ )

于 2012-12-22T03:33:50.720 に答える