1

私はこのコードを持っています:

var img = $('<img>')
.attr('src','a.jpg')
.load(function(){
    alert(img.width()) ;
}) ;

幅は常に 0 です。

自然な幅のサイズを取得するには?

ありがとうございました!

編集:私はconsole.log(img)だけで、 naturalWidthを見ましたが、
それを取得する唯一の方法は: img[0].naturalWidth です

http://jsfiddle.net/akkara/L9dMD/1/

4

1 に答える 1

1

The code you have written is right.

var img = $('<img>')
.attr('src','a.jpg')

// Correct till here
// Wrong after this!

.load(function(){
    alert(img.width()) ;
});

But, still it is not in the DOM as a layout. So, this won't work. What you need to do is, you need to place it in the DOM.

So, the best thing is, laying it inside the DOM and get the property.

var img = $('<img>')
.attr('src','a.jpg')
.appendTo('body');
alert(img.height());
img.remove();

Updated working fiddle:

$(document).ready(function(){
    var img = $('<img>')
        .attr('src','http://blog.tmcnet.com/blog/rich-tehrani/uploads/new-microsoft-logo.png')
        .css('visibility', 'hidden')
        .appendTo('body');
    var imgHt = img.height();
    alert(imgHt);
    img.remove();
});

Fiddle: http://jsfiddle.net/praveenscience/KpCRe/

于 2013-01-26T13:06:04.283 に答える