Javascript Image()返回错误的宽度和高度

时间:2013-05-09 18:21:40

标签: javascript jquery jquery-plugins

我正在使用Cross-Slide Jquery Plugin而我有疑问。

当我尝试加载尺寸为1176 x 1168的图像时,.width属性返回600而.height属性返回595.

为什么不返回我图片的当前尺寸?

插件代码:

 // first preload all the images, while getting their actual width and height
    (function (proceed) {
        var n_loaded = 0;
        function loop(i, img) {
            // for (i = 0; i < plan.length; i++) but with independent var i, img (for the closures)
            img.onload = function (e) {                
                n_loaded++;

                // Here are my doubt
                plan[i].width = img.width; // returning 600
                plan[i].height = img.height; // returning 595
                if (n_loaded == plan.length)
                    proceed();
            }
            img.src = plan[i].src;
            if (i + 1 < plan.length)
                loop(i + 1, new Image());
        }
        loop(0, new Image());

    })(function () {  // then proceed ...

2 个答案:

答案 0 :(得分:0)

你尝试过这样吗?

var img = document.getElementById('imageid'); 
var width = img.clientWidth;
var height = img.clientHeight;

答案 1 :(得分:0)

您需要稍微修改一下代码(主要是loop函数)并重试,如下所示:

function loop(i, img) {
    img.src = plan[i].src;
    img.onload = function (e) {
        n_loaded++;
        plan[i].width = this.width; // Check the width now
        plan[i].height = this.height; // Check the height now
        if (n_loaded == plan.length) proceed();
    }
    if (i + 1 < plan.length) loop(i + 1, new Image());
}

SIMPLE DEMO HERE