jQuery - 获取图像的宽度

时间:2012-04-04 18:19:53

标签: jquery css image width

我正在尝试获取图像的实际宽度...这里是有问题的图像

<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,它们将有不同的宽度,我的问题是,我如何获得这些宽度?

谢谢, Ĵ

4 个答案:

答案 0 :(得分:1)

这应该使用所有图像的宽度填充数组:

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

答案 1 :(得分:0)

如果#slideshow包含多个img,则您对$("#slideshow").find("img").width();的调用只会返回第一个img宽度,在这种情况下,必须为200

答案 2 :(得分:0)

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

答案 3 :(得分:0)

我会给你一个你没有要求的答案 - 但我认为这是更好的解决方案。

只是因为我发现你在图像中使用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" />