开发者

How to add dimensions to dynamic img elements

I use a Json call to get a list of image addresses, then I add them individually to a div like this. Unfortunately the image dimension is not part of the Json information.

<div id="container">
   <img src="A.jpg" alt="" />
   <img src="B.jpg" alt="" />
   ...
</div>

Do any of you JQuery geniuses know of a code that would flawlessly and dynamically add the true Width and Height to each img element in the container as soon as each individual one is rendered?

I was thinking maybe the code could do a image width check width > 0 to evaluate when the image has actually been rendered, then fire. But I wouldn't know how to go about that and make it work stably. How is the best way of going about this?

Update, As the answers point out, adding Width or Height to the elements is pretty routine. The problem here is actually writing a code that would know when to do that. And evaluate that condition for each image not the page as a whole.

Update 2

I f开发者_Python百科ound a very nice working answer here


Yes, you can, you can use the width() and height() methods to get the dimensions of the images. Thanks to JQuery.

More Info:

  • width()
  • height()

Update Baded On Comment:

The load even is fired when all images and external resources have loaded into the page along with the DOM, so you can use that and use the width() and height() methods to get the dimensions of the images. Example:

$(window).load(function(){
  // your code to get dimensions, manipulate images, etc
})


try this:

$('#container img').css('height', function(index, value){
    return $(this).height()+ 'px';
})
$('#container img').css('width', function(index, value){
    return $(this).width() + 'px';
})

EDITED

ok, I have tried something like this and when I inspect the elements using firebug, height and width attribute is there withe right values....

$(document).ready(function(){

  $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
        function(data){
          $.each(data.items, function(i,item){
            $("<img/>").attr("src", item.media.m).appendTo("body");
            if ( i == 999 ) return false;
          });
          $('img').css('height', function(index, value){
              return $(this).height()+ 'px';
          });
          $('img').css('width', function(index, value){
              return $(this).width()+ 'px';
          });
  });
})

demo


Use $(document).ready() to wait for the images to be completely loaded.

ready (handler)

handler - A function to execute after the DOM is ready.

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received.

Reigel's solution, now with the use of $(document).ready():

$(document).ready(function() {
    $('#container img').css('height', function(index, value){
        return $(this).height()+ 'px';
    });
    $('#container img').css('width', function(index, value){
        return $(this).width() + 'px';
    });
});

[EDIT]: Just realized that this may not work when you insert the images after the page has loaded but I guess it's worth a try:

$('#mydiv').html('<img .../><script language="javascript" type="text/javascript">$(document).ready(...)</script>');


$('#container img').each(function(){
var pic_real_width;
var pic_real_height;

$(img).load(function() {
    // Remove attributes in case img-element has set width and height
    $(this).removeAttr("width")
           .removeAttr("height")
           .css({ width: "", height: "" }); // Remove css dimensions as well

    pic_real_width = this.width;
    pic_real_height = this.height;
});

var src = img.src;
img.src = "";
img.src = src; // Triggers onload if image is cached
});

Credit goes to Xavi


Another suggestion:

Load the images via AJAX in the background and hope for the browser to cache them, so that they are instantly there when you add the elements to your div (and you can retrieve width() and height() immediately). ;)

If you have any access to the webserver which sends those images: Make sure you set the appropriate cache headers.

[EDIT]: Instead of relying on the cache you could also put the image data, which you just loaded via AJAX, directly into your source code. Unfortunately, this apparently doesn't work in IE.

<img src="data:<mimetype>;base64,<data>" />

To encode the data use a function like this one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜