Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

html - Getting auto size of IMG before adding it to DOM (Using JQuery)

I'm dynamically adding IMG components to my DOM using JQuery, but depending on how big they are, I'll be adding them in different ways. Anyone have a good idea for getting the IMG's auto sized dimensions BEFORE I add it to the DOM?

NOTE: I was playing around with DOM snippet JQuery manipulation, as described here, but the img dimensions were = 0.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

DOM elements have dimensions only when added to a parent, as dimension is determined by the rendering engine. To go around this issue, have a <div> container absolutely positioned off screen, add the image to it first, get the dimension, then add the image at it's final destination.

Something like :

var _offscreen = $('<div></div>')
    .css({position:'absolute',left:'-999999px',width:'400px',height:'600px'})
    .appendTo($('body'));

var img = $('<img>/img>')
    .attr('src',"http://l1.yimg.com/a/i/ww/news/2011/03/25/zo.jpg")
    .load(function() {

      var $this = $(this);
      $this.appendTo(_offscreen);

      setTimeout(function() {
         var width = $this.width();
         var height = $this.height();

         alert($this.attr('src') + ' = ' + width + "x" + height);      
      }, 0);
});

** EDIT **

I just updated the code above. As it turned out, you need to let the rendering engine draw the image (of course!) and then get the dimension. So that edit works.

This could be put inside a convenient function like :

$('imageElement').loadImage("path/to/image", function() {
   alert("Image " + $(this).attr('src') + " loaded: " + $(this).width() + "x" + $(this).height());
});

** UPDATE **

I thought you might like to see the code above put into a JQuery plugin... just for fun :) It just works, there is no validation done (i.e. it won't check if you pass other elements than <img>), and if the selector returns more than one element, the plugin will load the same image into each selected elements. You could actually have the plugin argument url be an array (optional) and load each image of the array in each selected element, etc. Just a thought.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...