0

警报有效,但返回值为 0。如何让它返回正确的值?

var img;
img = new Image();
img.onload = function() {
   alert(img.width);
   return(img.width);
};
img.src = "https://maps.gstatic.com/mapfiles/dir/bike.png";
alert(img.width);
4

3 回答 3

3

You can't do that. onload runs once the image is loaded, which means after setting the src, onload will run later.

You need to put all code dealing with the image's width inside the onload.

于 2012-06-07T15:41:53.263 回答
2

You can return the value, but you have no way of capturing it.

The function you pass to onload is executed, when your image has loaded. But there is no way to retrieve the return value there. You can just call another function inside, to process the value.

于 2012-06-07T15:42:39.590 回答
0

10从 Chrome 中的这段代码中得到:

var img = new Image();
img.onload = function() { console.log(img.width); }
img.src = "https://maps.gstatic.com/mapfiles/dir/bike.png";

在查询宽度(in )之前,您必须等待图像加载onload

于 2012-06-07T15:44:36.627 回答