在加载和就绪事件之前,将图像大小获取到全局变量中
Get image size into a global variable before load and ready events
我在获取图像宽度并将其保存到全局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
-函数内,否则它将过早运行。
相关文章:
- 获取ajax加载的图像的大小
- 点击(右键点击)使用传单地图库获取图像覆盖的像素坐标
- 如何使用javascript和xpath获取图像src
- 如何使用javascript从文件夹中获取图像并发布直接链接
- 如何使用Pixijs获取在加载的精灵表资产中定义的图像
- 如何从 javascript 中可能具有一个或多个图像的字符串中仅获取图像名称
- 获取图像节点js的主色
- 获取图像的平均外部像素颜色
- 使用asp.net FileUpload时从javascript获取图像宽度和高度
- 如何获取显示在谷歌搜索右侧的图像链接
- CodeIgniter:用于获取包括图像在内的值的控制器
- jQuery:获取图像加载错误的详细信息
- 如何使用php和javascript获取网页中显示图像的路径
- 使用回调获取图像像素数据
- 使用JavaScript从外部图像获取颜色
- 将完整路径图像获取到输入文件中
- 如何利用织物画布上的背景图像获取绘图路径中的图像
- 无法将图像加载到画布中并为该图像获取base64编码
- Android从内部图像获取ImageData()-SECURITY_ERR:DOM异常18
- 将html转换为图像(获取dom的快照)