在加载和就绪事件之前,将图像大小获取到全局变量中

Get image size into a global variable before load and ready events

本文关键字:图像 获取 全局变量 加载 就绪 事件      更新时间:2023-09-26

我在获取图像宽度并将其保存到全局var 中时遇到问题

我在早上做这个

var imgWidth;
var imgLoad = $("<img />");
imgLoad.attr("src", "Images/animals.jpg");
imgLoad.off("load");
imgLoad.on("load", function () {
  imgWidth = this.width;
  console.log(imgWidth); // It works! Inside function scope
});

console.log(imgWidth); // It doesn't work! Outside function scope

我知道它不起作用,因为我试图在设置var的范围之外显示值。

图像不会显示,我只需要宽度和高度使用一个src。在未来的函数中,我需要图像宽度和图像高度,所以这就是为什么我需要至少将其保存到全局变量中。

我该如何解决?

非常感谢

imgWidth在函数外是未定义的,因为它只是一个空变量,您不添加任何内容,只是在顶部声明它。为了让它发挥作用,你需要做一些类似的事情

var imgWidth,
    imgLoad = $("<img />");
imgLoad.attr("src", "http://www.gettyimages.com/CMS/Pages/ImageCollection/StaticContent/image5_170127819.jpg");
imgLoad.on("load", function () {
  imgWidth = this.width;
  console.log('Inside Function:'+imgWidth);
});
imgWidth = imgLoad[0].width;
console.log('Outside Function:'+imgWidth); 

此处的工作示例http://jsfiddle.net/kanzvoap/

您对范围没有问题,但对时间没有问题。函数外部的console.log()确实看到变量imgWidth,因为其在函数外部声明了。它只是没有分配值,所以undefined被记录。加载图像后,值(宽度)将被分配。加载需要一些时间,但代码不会等待,因此最后一行在imgwidth获得值之前执行。

查看以下内容:

var imgWidth;
var demo = 'demoValue';
var imgLoad = $("<img />");
// attach the event-handler BEFORE you set the src-attribute, otherwise it may happen
// that image is loaded before and the onload-function won't work
imgLoad.on("load", function () {
    imgWidth = this.width;
    // all variables declared outside are visible here
    console.log('inside: ', imgWidth); // --> inside: some px
    consolole.log('inside: ', demo); // --> inside: 'demoValue'
});
imgLoad.attr("src", "Images/animals.jpg");
// all variables declared outside a function are also visible here,
// but this runs before the image has finished loading
console.log('outside: ', imgWidth); // --> undefined only because it has no value at this time
console.log('outside: ', demo); // --> 'demoValue'
// now wait a second using a setTimeout
window.setTimeout(function() {
    // all vars are visible here, but now image is loaded and var imgwidth has got its value
    console.log('outsideLater: ' + imgWidth); // --> some px
    console.log('outsideLater: ' + demo); // --> 'demoValue'
}, 1000);

因此,结果是:您的var声明是可以的,但所有应该对图像或其属性执行操作的代码都必须在load-函数内,否则它将过早运行。