jQuery Ajax加载图像问题

时间:2010-03-13 05:10:20

标签: javascript jquery image css

我有一个代码可以调用$ .load()来获取HTML片段。在片段中将有一个图像列表和一个脚本,可以根据列表大小进行一些计算。片段看起来像

<div>
  <ul>
    <li><img .../></li>
    <li><img .../></li>
    ...
  </ul>
</div>

<script>
   //... script to do calculation on the list width
</script>       

最初,我使用css的max-width来确保图像不会超过180px。但由于IE没有max-width,我使用hack表达式。但是,当图像首次加载时,脚本无法获得正确的图像列表宽度。好像脚本加载的时间早于CSS表达式。

如果是新页面,我当然可以调用$(window).load()来确保加载所有图像。但是我可以在ajax html片段请求中做些什么呢?

1 个答案:

答案 0 :(得分:1)

DEMO: http://jsbin.com/ehawa/2

Javascript方法适用于 offsetWidth

  

es:document.getElementById(“UL_ID”)。offsetWidth

使用jQuery

示例工作代码

       <style>
        ul { list-style:none; margin:0; padding:0 }
        ul li { margin:10px }
        ul li img { /* width:180px */ }
        div { float:left; width:200px; background:#333 }
        </style>

      <script>
    $(function() {

        setImgWidth();

    });

// then Insert the same function After the Ajax Call

 function setImgWidth() {

    $('ul li > img').each(function() {
        //get it's width
        var img = $(this).width();
        if (img > 180) {
            $(this).attr('style', 'width:180px');
        }
    });

}
        </script>


    <div>
      <ul>
        <li><img src="http://l.yimg.com/g/images/home_photo_junku.jpg" alt=""/></li>
        <li><img src="http://l.yimg.com/g/images/home_photo_tarotastic.jpg" alt=""/></li>
      </ul>
    </div>
希望这有帮助!