【问题标题】:jQuery - get the width of an imagejQuery - 获取图像的宽度
【发布时间】:2012-04-05 02:43:42
【问题描述】:

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

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

谢谢, J

【问题讨论】:

标签: jquery css image width


【解决方案1】:

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

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

【讨论】:

  • .bind() 已过期,应改用 .on()api.jquery.com/bind
  • 嗯,这似乎不适用于我的图片
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    我将为您提供您没有要求的答案 - 但我认为更好的解决方案。

    只是因为我看到您在图像本身中使用 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" />
    

    【讨论】:

    • 从服务器获取实际图片的大小,我要找的是高度为200时图片的宽度
    【解决方案4】:
    var $imgs = $('img');
    $imgs.load(function(){
        console.log($(this).width());
    });
    

    【讨论】:

    • 当我检查元素时,没有出现宽度属性:(
    猜你喜欢
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 2014-02-12
    • 2011-10-21
    • 2012-01-28
    • 2023-04-03
    • 2012-07-15
    • 2012-11-05
    相关资源
    最近更新 更多