2012-04-04 123 views
2

我想获得的图像的实际宽度...这里是有问题的jQuery - 获得图像的宽度

<img src="upload/<?php echo $array['image'] ?>" height="200" class="active" /> 

形象,这是我在jQuery的

$(window).bind('load', function() { 
    var img_width = $("#slideshow").find("img").width(); 
    $("#slideshow img").css("width", img_width); 
    alert(img_width); 
}); 
尝试

警报返回255每次我有试过这个图像,这是div幻灯片的宽度。这些图像的高度都为200,他们将有不同的宽度,我的问题是,如何获得这些宽度?

感谢, Ĵ

+0

检查,这可能已经回答不已:http://stackoverflow.com/questions/2395931/how-do-i-get-actual-image-width-and-height-using-jquery – sakhunzai 2012-04-04 18:22:39

回答

0

如果#slideshow包含不止一个img,您的来电$("#slideshow").find("img").width();将只返回第一img宽度,在这种情况下,必须在200

1

这应该填充一个数组所有图像的宽度:

$(window).bind('load', function() { 
    var img_widths = []; 
    var imgs = $("#slideshow").find("img"); 
    imgs.each(function() { 
     img_widths.push($(this).width()); 
    }); 
}); 
+3

'。 bind()'是过时的,应该使用'.on()'来代替。 http://api.jquery.com/bind/ – Sparky 2012-04-04 18:29:28

+0

嗯,这并不似乎适用于我的图像 – user1274810 2012-04-04 18:31:05

+0

http://getfirebug.com/ – JoshNaro 2012-04-04 18:53:40

0
var $imgs = $('img'); 
$imgs.load(function(){ 
    console.log($(this).width()); 
}); 
+0

当我检查元素,宽度属性不会出现:( – user1274810 2012-04-04 18:34:47

0

我GOI恩给你你没有要求的答案 - 但我认为是更好的解决方案。

只因为我看到你正在使用PHP的图像本身 - 为什么不只是写用PHP imagesize信息。它更好,不会等待负载。

<?php 
// path from document root seems to work best for me 
list(, , , $attr) = getimagesize($_SERVER['DOCUMENT_ROOT'] . "/upload/".$array['image']); 
?> 
<img src="upload/<?php echo $array['image'] ?>" <?php echo $attr; ?> class="active" /> 
+0

那得到从服务器的实际图像的大小,我所期待的图像的宽度时,高度为200 – user1274810 2012-04-04 18:49:29