【问题标题】:Getting image width and height with jquery使用 jquery 获取图像的宽度和高度
【发布时间】:2012-04-04 23:05:14
【问题描述】:

我有一个非常简单的代码,令人讨厌的是它正在工作,而对于我来说,我不明白为什么它现在失败了:

function imageSize(img){
  var theImage = new Image();
  theImage.src = img.attr('src');
  var imgwidth = theImage.width;
  var imgheight = theImage.height;

  alert(imgwidth+'-'+imgheight);
}

传递的“img”变量是img对象,获取自:

jQuery('img')
.each(function(){
    var imgsrc = jQuery(this);
    imageSize(imgsrc);
});

【问题讨论】:

  • 嗯,究竟是什么问题?在我看来没问题。另外,你为什么使用成熟的词'jQuery'?兼容性问题?为什么不直接使用'$'?
  • 可能值得一提的是,如果在此代码运行时图像没有完全下载,那么宽度和高度将返回为零,或者可能是其他一些不正确的值。
  • 准确检测图像何时完全加载非常棘手,因为如果从缓存中提取图像,.load 事件将不会触发。有关此问题的解决方案,请参阅 this question

标签: jquery image height width


【解决方案1】:

好的——当我在 jsFiddle 上测试时,我给出的上一个答案是无效的——我创建了这个你想要的答案?您需要拥有“new Image()”部分吗? http://jsfiddle.net/R89Qr/3/ - 给图像一些硬编码的尺寸...

我稍微更改了您的代码,因此它可以这样做:

 function imageSize(img){
  var theImage = new Image(); // ignoring this part when checking the image width/height
  theImage.src = img.attr('src');
  var imgwidth = $(img).width();
  var imgheight = $(img).height();

  alert(imgwidth+'-'+imgheight);
}

$('img').each(function(){
    var imgsrc = jQuery(this);
    imageSize(imgsrc);
});

【讨论】:

  • 如果 theImage 是一个 jQuery 对象,那将是真的。
  • 是的 - v.true,我做了一些改动并添加了一个小提琴以使其工作。
  • 你找错树了。非 jQuery JavaScript image object 具有应该在原始代码示例中检索到的宽度和高度属性——如果图像在代码运行时已完全加载。
【解决方案2】:

图像可能尚未加载。所以,试试(未经测试):

function imageSize(img){
  var theImage = new Image();
  $(theImage).load(function() {
    var imgwidth = this.width;
    var imgheight = this.height;

    alert(imgwidth+'-'+imgheight);
  });
  theImage.src = img.attr('src');
}

【讨论】:

    【解决方案3】:

    你必须等待,直到你的图片被加载,然后访问它的大小:

    function imageSize(img){
      var theImage = new Image();
      theImage.onload = function(){
        var imgwidth = theImage.width;
        var imgheight = theImage.height;
    
        alert(imgwidth+'-'+imgheight);
      }
      theImage.src = img.attr('src');
    
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      相关资源
      最近更新 更多