1

我正在从 PHP 返回的 json 数据中加载大约 50 张图像。为了避免额外调用 PHP 获取图像大小,我想在客户端执行此操作。这可能吗?

这是我当前用于构建图像列表的 jquery 调用:

// Create HTML for the images.
var html = '';

$.each(data.profiles, function() {

    // Can I determine the img height or do I need to wait until the image is loaded?

    html += '<a href="/view_profile.php?id='+this.user_id+'">';
    html += '<img src="'+this.file_name+'" width="200" height="" style="border:0;">';
    html += '</a><br>';

});
4

2 回答 2

1

您可以绑定图像的加载事件并在客户端加载图像时获取它,如下所示:

$.each(data.profiles, function() {

    // Can I determine the img height or do I need to wait until the image is loaded?

    html += '<a href="/view_profile.php?id='+this.user_id+'">';

    var image = new Image();  
    image.src = this.file_name;
    image.onload = function() {
        var height = image.height;
    };

    var img = $("<img/>").css('border', 0).prop('src', image.src);
    html += img.wrap('<div></div>').html();
    html += '</a><br>';
});
于 2012-08-10T16:54:46.273 回答
0

试试这个:-

<img alt="photo-current" src="images/galleries/1/photo_1.jpg" id="photo-current"/>

<script type="text/javascript"> 
jQuery(document).ready(function($) {
      $("#photo-current").load(function() {
            var imageHeight = $(this).height();
            alert("image height " + imageHeight );
      });
});
</script>
于 2012-08-10T17:03:12.897 回答