【问题标题】:Auto-resize images with jQuery to fit container使用 jQuery 自动调整图像大小以适应容器
【发布时间】:2012-05-13 01:26:16
【问题描述】:

我正在尝试构建一个脚本来调整大于容器的图像大小:

  $('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)

【问题讨论】:

  • 文件大小是无关紧要的无用信息。除非使用缩略图脚本,否则图像已经下载,所以如果我点击查看完整尺寸,那么它将立即来自缓存。
  • 是的,它们的文件大小相同,因为它们是相同的图像,但我仍然想在图像上方的功能区中显示此信息...
  • 在 CSS 中有一种简单的调整大小的方法:img { max-width: 100%; } 当然,您不会以这种方式获得可点击的链接。
  • 请参阅this question 以获取有关此问题的提示。在完全达到.loaded 之前,您无法测量图像的尺寸(这就是为什么您将height() 设为零的原因),但是如果没有一点缓存,您将无法检测到它何时为.loaded额外的诡计。

标签: javascript jquery css image


【解决方案1】:

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

$(window).load(function() {
     // your code
});

【讨论】:

    【解决方案2】:

    试试这个:

    $('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 中测试。

    【讨论】:

      猜你喜欢
      • 2020-06-03
      • 1970-01-01
      • 2012-10-04
      • 2015-12-21
      • 2011-03-03
      • 2017-11-20
      • 2012-08-10
      • 2016-01-06
      • 2021-09-20
      相关资源
      最近更新 更多