How to get the image size in jquery
I have a simple image gallery with different image size. I'm going to get the width of 开发者_如何学Gothe current image and assign it to it's parent div using jquery but I can't seem to get it working. Thanks for any help.
var imgWidth = $("#image").width();
$("#gallery").css({ width : imgWidth });
Sample HTML:
<div id="gallery">
<img src="123.jpg" id="image" />
</div>
Your code seems ok. But you may be trying when the image hasn't been loaded yet. $(document).ready
wouldn't help in this case.
Try this:
$(window).load(function(){
var imgWidth = $("#image").width();
$("#gallery").width(imgWidth);
});
Hope this helps. Cheers
You need to specify "px"
Like so:
var imgWidth = $("#image").width();
$("#gallery").css({ width : imgWidth+"px" });
Assuming the image is loaded when your javascript is executing this should work. If not you'll have to place this code inside a $(window).load(function(){});
as Edgar says or possibly even a $("#image").load(function(){});
.
You're going to kick yourself for this......
Your jsfiddle was set to use mootools not jQuery.
Here's a working update link
精彩评论