从缩放图像中获取宽度

我将使用Jquery获取图像的宽度,一旦它附加到正文。 看看这个小提琴 ,了解我正在做的事情。

我想要做的是添加具有约束高度的每个元素,并在缩放后读取相应宽度的一次。 你会看到的问题是console.log给了我宽度值0。

使用jQuery .load()函数在图像加载后进行所有计算:

var number = 0;

 $(document).ready(function(){ setInterval(function(){ console.log(); $('.container').prepend( $('').attr({ src: "http://www.upress.umn.edu/book-division/images-1/other images/blockc.gif/image_thumb" id:'img' + (number++) }).load(function(){ console.log($(this).width()) }) },3000); });​ 

http://jsfiddle.net/w7rcn/

在图像完全下载之前,宽度被“读取”。

因此,我们使用相同的概念,但在img load事件触发后应用它:

  $('#img' + String(number)).load(function() { console.log($(this).width()); }); 

Mohsen和Justice是对的。 但是,您仍然可以简化一下:

 var number = 0; $(document).ready(function(){ setInterval(function(){ console.log(); $('.container').prepend($('').load(function() { console.log($(this).width()); })); number++; }, 3000); });​