我在尝试获取图像宽度并将其保存到全局变量
时出现问题我是在妈妈那里做这件事
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的宽度和高度。我将在未来的功能中使用图像宽度和图像高度,这就是为什么我需要将它至少保存到全局变量中。
我该如何解决?
非常感谢
答案 0 :(得分:1)
正如你所知,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);
答案 1 :(得分:0)
你对范围没有问题,但有时间。函数外的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
- 函数内,否则它会运行得太早。