[英]how to return a variable inside img.onload = function() in jquery?
让我们陷入困境:
这是我的代码:
function inside()
{
var gallery = $("#gallery");
var photo = $("#photo");
var width_mask = gallery.width(); //defines width for mask
var height_mask = gallery.height(); //defines height for mask
var img = new Image();
img.onload = function() {
var width_image = this.width;
var height_image = this.height;
var img_src = img.src;
if((width_image/width_mask)>=(height_image/height_mask))
{
height_image = ((width_mask/width_image)*height_image);
width_image = width_mask;
}
else if((width_image/width_mask)<(height_image/height_mask))
{
width_image = ((height_mask/height_image)*width_image);
height_image = height_mask;
}
var top_margin = (height_mask - height_image)/2;
var left_margin = (width_mask-width_image)/2;
photo.css({
marginTop : top_margin,
marginLeft: left_margin,
marginRight: left_margin
});
photo.attr('src',img_src);
photo.attr('width',width_image);
photo.attr('height',height_image);
gallery.css({
width : width_mask,
height : height_mask
});
};
img.src = photo.attr('src');
}
好的,您可以看到这是我的功能...这是我的问题:如何在img.onload函数中返回“ top_margin”和“ left_margin”变量?
好吧,实际上我知道我们如何在一个函数中返回变量,但是在这个onload函数中,它似乎不起作用:(
不好意思,我是Java语言的初学者...任何帮助将不胜感激。
非常感谢Naghme
您不能从onload中“返回值”,因为它是异步回调。
可以,但是没有意义,因为是浏览器调用onload()回调,并且对其返回值不感兴趣。
异步=不会立即执行,但会在将来某个时候执行
同步=将立即执行
使用回调处理异步性。 回调是一种通过将一个函数传递给另一个函数而起作用的机制,因此被调用方函数可以在将来的某个时间将完成的工作通知给调用方代码。
如果该函数同步工作,则可以简单地返回值而无需回调。 但是缺点是调用函数的代码必须等待从服务器加载图像,这可能需要很长时间,并且如果服务器的响应时间很长,则会使程序冻结很长时间。时间。 你不想那样做。
如果您像这样调用inside()函数:
inside();
您可以从onload返回值(或任何值),只要您异步执行即可。 您可以通过进行以下修改来做到这一点:
function inside(imageLoadedCb) {
// ...
img.onload = function () {
// ...
// notify the caller of inside() that image was loaded, with the values we want to return
imageLoadedCb(top_margin, left_margin);
}
}
inside(
// this is a function reference. it ends up in "imageLoadedCb" variable in "inside" function
function (top_margin, left_margin){
// this code gets invoked from inside the onload() callback
console.log('top_margin= ' + top_margin + ' left_margin= ' + left_margin);
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.