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

これを試して:

$('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 に答える
1

コードを $(window).load でラップします

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