2

我有一组动态获取的图像。对于我应用最大高度的每个图像,我使用它来调整大小。

我有一个 jquery re-size 函数:

// 调整我的图片大小

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 而不是实际宽度。但是,如果我测试图像使用萤火虫,我会得到正确的宽度。

注意:有时我得到正确的答案,但我刷新并再次得到 0。请问有什么建议吗??令人沮丧的是我花了几个小时在这上面..

4

2 回答 2

3

今天我正在编写一个 jQuery 插件,我遇到了同样的问题,所以我最终引用了 DOM 元素。尝试

$(this)[0].height代替myImage2.height()

$(this)[0].width而不是myImage2.width().

于 2012-12-22T03:53:11.317 回答
0

我认为正确的宽度可能来自于萤火虫的摆弄,并且刷新清除了所有摆弄。

你试过了吗:

 alert(myImage2.outerHeight());

在您显示的第二个代码和

var width = $(objct).outerWidth

在你的第一个代码中?( http://api.jquery.com/outerWidth/ )

于 2012-12-22T03:33:50.720 回答