javascript - JS : Determinining image dimensions only partially successful

标签 javascript jquery html css jsmovie

我正在使用 JS/HTML/CSS 创建一个小型 Web 应用程序,用户可以在其中使用下拉菜单从 13 个不同的图像中进行选择。选项 1 是默认值,当用户选择不同的选项时,应用程序将刷新,并且应用程序中其他对象的尺寸将调整为新图像的尺寸。

为了访问 13 个不同图像的图像尺寸(高度和宽度),JS 循环启动并将尺寸存储在两个数组中。

var height_array = []
var width_array = []

for (i = 1; i <= 13;i = i + 1) {
    var img = new Image();
    if (i <= 9){
        img.src = "img/rehe/RE0"+i+"/001.png";
    }
    else{
        img.src = "img/rehe/RE"+i+"/001.png";
    }
    height_array.push(img.height);
    width_array.push(img.width);
}

我不明白的是,循环仅部分时间成功,有时数组为空或仅部分填充。当然,应用程序的构建完全错误。在这种情况下刷新会有所帮助,但仍然很烦人。

我在这里有这个非常简单的应用程序的预版本:http://wieselundco.ch/plenum2/index.html提前致谢!

最佳答案

必须先加载图像,然后才能获取尺寸

var height_array = []
var width_array  = []

for (i = 1; i <= 13;i = i + 1) {
    (function(j) {
        var img = new Image();

        img.onload = function() {
            height_array[j] = img.height;
            width_array[j]  = img.width;
        }

        if (img.complete) img.onload();

        if (j <= 9){
            img.src = "img/rehe/RE0"+j+"/001.png";
        } else {
            img.src = "img/rehe/RE"+j+"/001.png";
        }
    })(i);
}

关于javascript - JS : Determinining image dimensions only partially successful,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29953628/

相关文章:

javascript - 如何在 Node.js 中追加到 Buffer

html - Bootstrap 等高列中断响应

javascript - 如何使图像和镜头旋转与 BlowupJS 保持同步?

java - 丰富的 :effect usage problem

jquery - Html 表单没有在 GET 上向 URL 添加参数

javascript - Jquery Clone 克隆表单问题

php - 从 JSON 获取结果,JQUERY 无法正常工作

javascript - 无限水平 slider 显示多张幻灯片,悬停时带有暂停动画

javascript - OnClick 时获取 JavaScript 或 JQuery 值中的复选框

javascript - 页面过渡