Getting the width of an image without an assigned width using jquery
I have the following code which needs to get the width of an image which is dynamically loaded, when a thumbnail is clicked on.
$("<img class='mypopupimage' src='" + imgSrc + "' style='padding:10px;' width='500' />").appendTo("div.myd开发者_StackOverflow中文版iv");
var imgWidth = $(".mypopupimage").width();
The trouble I have is that the popup images are all different widths, but when I remove the width attribute from the image the imgWidth variable gets set to 0.
Any ideas?
This has already been answered multiple times on stack, however, here it is for ease:
clientWidth and clientHeight are DOM properties that show the current in-browser size of the inner dimensions of a DOM element (excluding margin and border). So in the case of an IMG element, this will get the actual dimensions of the visible image.
var img = document.getElementById('imageid');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
This answer is taken from here
You should use the attribute naturalWidth if you want to use jQuery or go with the "normal" javascript as stated by udjamaflip:
$("<img class='mypopupimage' src='" + imgSrc + "' style='padding:10px;' width='500' />").appendTo("div.mydiv");
var imgWidth = $(".mypopupimage").attr('naturalWidth');
精彩评论