1

我有这样的代码

<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> 但不起作用,

4

1 回答 1

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

补充:小提琴

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

于 2013-05-12T03:52:29.503 回答