2017-02-02 3 views
0

Tumblrのために作成したスクリプトがあります。これはインライン画像のimg srcの一部を変更します(テキスト/キャプション/ etcの投稿、写真/写真ポスト)を大きく表示すると、Tumblrに読み込まれたデフォルトのURLは500ピクセル以下に強制され、多くの画像はしばしば大きくなり、コンテナを埋めるために引き伸ばすことができます。しかし、時には大きな画像のURLが常に利用できるとは限りません。そのURLを変更するとその特定の画像を取り消す方法があるかどうかを知りたがっています。これは私が持っているものですが、それはページ上の点滅:(私は追加誤差関数は含まない)元のコードと結果が画像URLを壊さない限り、img srcを変更する方法

$(window).on("load", function(){ 
$('.tmblr-full img').each(function(){ 
    var $this = $(this) 
     $this.attr('src',$this.attr('src').replace('_500.','_540.')) 
    if ($(this).width() >= 500) { 
     $(this).css({'width' : 'auto', 'height' : 'auto'}); 
    } 
}) 

$('.tmblr-full img').error(function(){ 
    var $this = $(this) 
     $this.attr('src',$this.attr('src').replace('_540.','_500.')) 
}) 

}); 

Here is a JSFiddleあなたが問題を見ることができるようにします。

ありがとうございました!

+0

イメージが終了しない場合、どのようなURLが返されますか? –

+0

@TonyHenslerそれは何も返されません、イメージは単に壊れます。 – agustd

答えて

1

、私がチェックするために、AJAXを使用した場合、新たな画像URL (エラーコードは返されません)、ajax呼び出しが成功した場合にのみURLを変更します。

$(".tmblr-full img").each(function(){ // for every img inside a .tmblr-full 

    var img = $(this), // define the target image 
    newSrc = img.attr("src").replace("_500.","_540."); // the image source to check 

    $.ajax({ // run an ajax check on the new image source 
    url:newSrc, 
    success: function(){ // if the image is found 
     img.attr("src",newSrc); // replace the old url with the new one 
    } 
    }); 

}); 

(フィドル:https://jsfiddle.net/48hpeo9z/7/

しかし、Tumblrのは、その<figure>タグ付き画像の元の幅が含まれているため、あなたはまた、画像の拡大版が存在するかどうかをチェックするためにそれを使うことができます。

0

URLを文字列から別の文字列に変更しています - システムは、2番目の文字列がエラーを引き起こすかどうかをどのように知ることができますか?

でし行うが、そのIMGの属性に以前のURL値を保存するだけでなく、またonload and onerror handlers of that particular image, as in this example再定義することです。次に、エラー状態が発生した場合、onloadとonerrorの両方をクリアして、前のsrc値を再設定します。

私は現在、それを試してみることができないんだけど、ここではそれが行く

:-)私の試み:

私の方法については
$('.tmblr-full img').each(function(){ 
    var $img = $(this); 
    var img = $img[0]; 

    // Save the original src 
    $img.attr('orig-src', $img.attr('src')); 

    img.onerror = function() { 
     var $img = $(this); 
     var orig = $img.attr('orig-src'); 
     $img.attr('orig-src', null); 
     $img.attr('src', orig); 
    }; 
    img.onload = function() { 
     var $img = $(this); 
     if ($img.width() >= 500) { 
      $img.css({'width' : 'auto', 'height' : 'auto'}); 
     } 
    } 
    // Now try loading. 
    // If I remember correctly this will either fire onload 
    // or onerror. 
    img.attr('src', $this.attr('src').replace('_500.','_540.')); 
}) 
+0

残念ながら、私はまだJavascriptの何もないことをほとんど知っています。これを既存のスクリプトにどのように組み込むか、それを新たに書き込むのですか?どうもありがとうございます! – agustd

+0

申し訳ありませんが、最後の行は$ imgではなくimgです。私は明日私のPCから修正します。 – LSerni

+0

私はスクリプトをテストしたが動作しません。 :(ここからご覧いただけます:https://jsfiddle.net/jeongguk/48hpeo9z/3/ – agustd

関連する問題