我正在使用 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/