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

Javascript Image() return wrong Width and Height

本文关键字:高度 错误 Image 返回 Javascript      更新时间:2023-09-26

我正在使用交叉幻灯片Jquery插件,我有一个疑问。

当我尝试加载尺寸为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 ...

你需要修改一下你的代码(主要是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());
}

简单演示

你试过了吗?

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