警报有效,但返回值为 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);
警报有效,但返回值为 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);
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
.
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.
我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
。