1

我正在尝试构建一个脚本,该脚本可以对大于容器的图像进行浏览器调整:

  $('img').each(function(i){
    var parent_width = parseInt($(this).parent().width()),
        image_width = parseInt($(this).width());

    if(parent_width !== image_width){
      $(this).width(parent_width).wrap(
         '<a class="resized-image" href="' + this.src + '">'
       + ' <span class="msg">'
       + '   This image has been resized to ' + parent_width + ' pixels'
       + '   and ' + $(this).height() + ' pixels'
       + '</span>'
       + '</a>'
      );
    }
  });

调整大小有效,但我怎样才能在那里得到一个很好的消息,告诉用户原始图像大小、图像调整大小的百分比以及原始图像大小(以 KB 为单位)?

喜欢

此图像已调整为 400 x 300 (50%)。原始图像有 800 x 600 和 75 KB。点击查看原文

到目前为止,我只能计算出调整后图像的宽度(height() 由于某种原因返回 0)

4

2 回答 2

1

用 $(window).load 包装你的代码

$(window).load(function() {
     // your code
});
于 2012-05-03T14:38:19.410 回答
1

尝试这个:

$('img').one('load', function () {

    var parent_width = parseInt($(this).parent().width()),
        image_width = parseInt($(this).width());

    if(parent_width !== image_width){
      $(this).width(parent_width).wrap(
         '<a class="resized-image" href="' + this.src + '">'
       + ' <span class="msg">'
       + '   This image has been resized to ' + parent_width + ' pixels'
       + '   and ' + $(this).height() + ' pixels'
       + '</span>'
       + '</a>'
      );
    } 

});

$('img').each(function () {
     //If image is cached by browsers, trigger .load()
    if (this.complete){        
         $(this).trigger('load');
    }
 });
​

jsfiddler中测试。

于 2012-05-03T16:37:13.973 回答