宽度和图像的高度都为零,因为异步图像加载的 [英] width and height of image are zero because of asynchronous image loading
问题描述
我长的base64 string类型我得到我想要设置为
的src
的图片
$('#IMG')。ATTR('src'中,base64data)
的console.log('高度 - '$('#IMG')的高度());
的console.log('宽 - '$('#IMG')的高度());
它看起来像即时得到回 0
为高度
和宽度
。当然,如果我等一会儿
然后我会得到适当的高度。
问题是 .attr()
没有一个回调,我将如何获得关于获取高度和宽度 SRC <后/ code>属性设置没有得到
0
回来。 (我觉得我得到0,因为jQuery中的变化发生异步,但我不能太肯定)
$('#IMG')。一('负荷',函数(){
的console.log('高度 - '$(本).height());
的console.log('宽 - '$(本).WIDTH());
})
.attr(src'中,base64data);/ *如果这个图像已经缓存负载的事件不能被解雇:
*然后寻找完整的状态,并触发加载事件
* /
如果($('#IMG')。得到(0).complete){
$('#IMG')触发('负荷')。
}
让之前宽度
和高度
则需要等待负荷
事件。
请注意,我用一()
方法,因为如果图像已经缓存应该不火的负荷
事件两次
I have a long base64
type string I get and I'd like to set as the src
of the image
$('#img').attr('src',base64data)
console.log('height - ' $('#img').height());
console.log('width - ' $('#img').height());
It looks like im getting back 0
for both height
and width
. Of course if I wait a while
then i'll get the proper height.
The thing is .attr()
doesn't have a callback, how would I get about getting the height and width after the src
attribute is set without getting 0
back. (I think i'm getting 0 because the change in Jquery is happening asynchronously but I cant be too sure)
$('#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');
}
Before getting width
and height
you need to wait the load
event.
Note that I used one()
method, because if the image is already cached it should not fire the load
event twice
这篇关于宽度和图像的高度都为零,因为异步图像加载的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!