应用图像高度和宽度的文本

时间:2013-05-12 03:33:16

标签: javascript

我有这样的代码

<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>

我想在<span id='u'></span>中应用图片的文字宽度和高度 但不起作用,

1 个答案:

答案 0 :(得分:2)

你必须等待图像完全加载..

所以HTML是

    <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>

将代码应用为

<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>

修改:如果图像获取缓存图片加载事件无法正确触发,  添加了重置src的代码

已添加:Fiddle

http://www.stoimen.com/blog/2009/08/05/jquery-check-whether-image-is-loaded/