I am displaying a profile image. If that image is bigger than certain dimension I want to scale it so I attach an onload
event to that image. After the image has loaded I will check whether it is greater and if so then I will scale it to a smaller image. I am displaying a loading animation till the image loads.
<td height="203" valign="middle" align="center"><div id="loadingdiv">Loading...
</div><img style="display:none;" id="proimg" src="<?=$path?>" />
</td>
<script type="text/javascript">
var pro = document.getElementById('proimg');
pro.onload = function()
{
if(this.width>260)this.style.width = '260px';
if(this.height>200)this.style.height = '200px';
window.setTimeout(function() {
document.getElementById('loadingdiv').style.display = 'none';
this.style.display = 'inline';
},1000);
}
</script>
The loading animation will fade and the image will be visible after a second. That is what I want so I did it like the above, but how to refer the this of onload
into settimeout
event handler?
Without the settimeout
it works fine and I can go with that but I just want to show a delay.
EDIT:
I use to do like the first reply, but I thought that there should be another way or concept of doing this.
IS THERE ANYTHING I CAN DO WITH CLOSURES HERE? SO THAT I DON'T HAVE TO USE EXTRA VARIABLE REFE开发者_开发问答RENCES.
You cannot use the this keyboard inside an anonymous event handle function, but you can still make a reference of the current this and then use that reference to call the methods/properties on the object. Here's an example :
var that = this;
window.setTimeout(function() {
that.style.display = 'inline';
}, 1000);
精彩评论