-1

我处于需要以这种方式解决的情况;需要将 a 转换local variable为 a global variable。有一个示例返回图像的真实宽度和高度,我从这个答案中找到了这些方法。.

需要将局部变量转换为全局变量pic_real_heightpic_real_width返回其真实值。

这是jsFiddle。

CSS:

img { width:0px; height:0px; }​

jQuery :

console.log($('.imgCon img').height());//returns 0

var img = $('.imgCon img')[0]; // Get my img elem
var pic_real_width, pic_real_height;
$('<img/>').attr('src', $(img).attr('src')).load(function() {
        pic_real_width = this.width;   
        pic_real_height = this.height;

        console.log( pic_real_width + 'x' + pic_real_height );
        // -- returns true 570x320 --
});
//problem starts here:
console.log( pic_real_width + 'x' + pic_real_height );
//returns undefined
// need to return this as an global variable 570x320
4

2 回答 2

2

这条线,

console.log( pic_real_width + 'x' + pic_real_height );

不等待这些行

    pic_real_width = this.width;   
    pic_real_height = this.height;

    console.log( pic_real_width + 'x' + pic_real_height );
    // -- returns true 570x320 -- 

执行,因为它是异步的。

因此, console.log( pic_real_width + 'x' + pic_real_height );在回调函数被调用之前执行(即在你设置widthand之前height)。

因为,您还没有定义它们,所以它们显示undefined.

一个简单的解决方案是,

$('<img/>').attr('src', $(img).attr('src')).load(function() {
        pic_real_width = this.width;   
        pic_real_height = this.height;

        console.log( pic_real_width + 'x' + pic_real_height );
        // -- returns true 570x320 --
        restOfMyProcessing();

}); 

function restOfMyProcessing() {
    console.log( pic_real_width + 'x' + pic_real_height );
}
于 2012-08-04T21:28:42.270 回答
0

在图像加载事件中设置之前,您尝试使用 pic_real_width 和 pic_real_height。
就像在您的代码中一样,第一个alert( pic_real_width + 'x' + pic_real_height )是在图像加载函数之后返回undefined的,第二个alert在加载事件中返回您所期望的。
虽然最好在加载函数/事件之后移动源属性的设置:

$('<img/>')
.load(function() {
    pic_real_width = this.width;
    pic_real_height = this.height;

    alert( pic_real_width + 'x' + pic_real_height );
    // -- returns true 570x320 --
    //now continue process here or call another function...
})
.attr('src', $(img).attr('src'));
于 2012-08-04T21:41:28.110 回答