开发者

How can i get the width/height of an image before appending that to the DOM/browser?

开发者 https://www.devze.com 2023-03-29 05:39 出处:网络
i would like to output the width and height of an image before appending that to the browser. Of course, i get 0 for the width and 0 for the height,开发者_如何学Go cause the image is not appended to t

i would like to output the width and height of an image before appending that to the browser. Of course, i get 0 for the width and 0 for the height,开发者_如何学Go cause the image is not appended to the DOM yet.

I have uploaded my code to http://jsfiddle.net/BF5En/4/

How can i take the right values before appending the image to the DOM??

Thanks, in advance!


You seem to have very interesting questions. This is my humble answer:

$(document).ready(function() {
    $(".Photos a").click(function () {
        var href_attribute = $(this).attr('href');
        var new_item = $('<img src="' + href_attribute + '" />')
            .hide()
            .load(function () {
                alert('Img was loaded! Width: ' + this.width + ' and height: ' + this.height);
            })
            .fadeIn(2000)
            .appendTo('.AppendingDiv');
        return false;
    });
});

Live example: http://jsfiddle.net/hobobne/BF5En/10/

You see, you must make sure that the image is preloaded, for that we use .load(). Otherwise you will get 0. That's actually good, because it means that the script works, just everything is so fast, that it can get the dimensions. .load() makes sure that the image is first loaded and only then receive the dimensions.

For whatever purposes you wanted to use the dimensions, I recommend doing that inside the .load() as well. Because you probably will have multiple .Photos a anyways.

Also, as you might have noticed your .fadeIn(2000) was not working. That's because, your item got appended before you called it. As you can see, I fixed it for you :)

NB! Sorry, I renamed some of the variables (made stuff more logic in my head.)


var MyitemWidth = item.css('width');
var MyitemHeight = item.css('height');

see this answer Getting auto size of IMG before adding it to DOM (Using JQuery)

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.
0

精彩评论

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