2012-05-22 43 views
4

我有很长的base64字符串类型我得到的,我想设定为图像宽度和图像的高度是零,因为异步图像加载的

$('#img').attr('src',base64data) 
console.log('height - ' $('#img').height()); 
console.log('width - ' $('#img').height()); 

它看起来像即时得到回来的src0对于heightwidth。当然,如果我等一会 那么我会得到适当的高度。

事情是.attr()没有回调,我将如何得到有关获取src属性设置后没有得到0返回的高度和宽度。 (我觉得我得到0,因为jQuery中的变化是异步发生的事情,但我不能太肯定)

+0

你有没有试过'.load()'-callback? –

+0

没有,但即时通讯给了这个镜头,它明显好于我想要的resize事件处理程序 – Akshat

回答

11
$('#img').one('load', function() { 
    console.log('height - ' $(this).height()); 
    console.log('width - ' $(this).width()); 
}) 
.attr('src',base64data); 

/* if this image is already cached load event couldn't be fired: 
* then look for "complete" status and trigger load event 
*/ 
if ($('#img').get(0).complete) { 
    $('#img').trigger('load'); 
} 

越来越width之前和height需要等待load事件。 请注意,我用one()方法,因为如果图像已被缓存,它不应该发射load事件两次

+0

只要确保你知道“使用图像加载”事件的注意事项“(在[load 'API](http://api.jquery.com/load-event/)) –

+0

发布更新以管理已缓存的图像 – fcalderan

+0

是.one还是.on?这在我的具体例子'one()'中虽然 – Akshat