find the dimensions of a dynamically loaded but DOM-appended image using jquery?

时光总嘲笑我的痴心妄想 提交于 2019-12-10 21:36:04

问题


I'm loading the source of an image dynamically using ajax, where s is this source. I create an image element in the DOM, assign it this source once it's loaded, and then append it to a div called imgwrapper. Then I try to get the image's dimensions, but it doesn't work. I'm aware you can't get the dimensions of an image that's dynamically loaded, but not even after being appended to the DOM?

My code is as below:

//use ajax to get value of s (the image source)
img = document.createElement("img"); 
img.src = s; 
$('#imgwrapper').appendChild(img); 
console.log($('#imgwrapper').find('img').width());

this returns 0, instead of giving me the image's width.


回答1:


Wait till the image has finished loading

//use ajax to get value of s (the image source)
img = document.createElement("img"); 
img.onload = function() {
    console.log($('#imgwrapper').find('img').width());
};
img.src = s; 

$('#imgwrapper').append(img);

Edit
As @MattiasBuelens mentioned. There is no .appendChild() for a jQuery object. That should be .append() instead




回答2:


You can try this:

img = document.createElement("img"); 
img.src = "http://placehold.it/350x150"; 
$('#imgwrapper').append(img); 
console.log($('#imgwrapper').find('img').width());

Working example: http://jsbin.com/adajuh/1/



来源:https://stackoverflow.com/questions/14335503/find-the-dimensions-of-a-dynamically-loaded-but-dom-appended-image-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!