I have code like this
<script src='js.js'></script>
<script>
(function($){
var img = document.getElementsByClassName('x'),
L = img.width(),
T = img.height();
for (var i=0,len=img.length;i<len;i++){
img[i] = $('#u').text("Width" + L + "Height " + T)
}
});
</script>
<div id='image'>
<img class='x' src='1.jpg'/>
<span id='u'></span>
</div>
<div id='image'>
<img class='x' src='5.jpg'/>
<span id='u'></span>
</div>
i want to applying text width and height of image in <span id='u'></span>
but does not work,
You have to wait for the image to get fully loaded..
So HTML is
<div id='image'>
<img class='x' src='1.jpg'/>
<span id='u'></span> </div> <div id='image'>
<img class='x' src='5.jpg'/>
<span id='u'></span>
</div>
Apply the code as
<script type="text/javascript">
$(document).ready(function(){
// reset src back to original..so that it works on cached images
$('img').each(function()
{
$(this).attr("src",$(this).attr("src")+"?_="+Math.random());
});
$('img').load(function()
{
var h = $(this).height();
var w = $(this).width();
// nearest span ..set its text
$(this).parent().find('span').html("Height :"+h +"_ _ _"+"Width :"+w);
}
); //end img load
});
</script>
Edit : If image get cached image load event doesn't fire correctly, added code to reset the src
Added : Fiddle
http://www.stoimen.com/blog/2009/08/05/jquery-check-whether-image-is-loaded/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.