除非结果破坏图像,否则如何修改 img src url

how to modify img src unless the result breaks the image url

我有一个专为 Tumblr 编写的脚本,它修改了内联图像中的部分 img src(在 text/caption/etc 帖子中,而不是 photo/photoset 帖子中)以显示更大,因为默认 url 加载到 Tumblr 中强制它们为 500px 或更小,许多图像通常更大并且可以拉伸以填充它们的容器。然而,有时用于较大图像的 url 并不总是可用,我想知道如果更改 url 会破坏它,是否有办法取消该特定图像上的脚本。这是我的,但是它在页面上闪烁:

$( 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加上原代码(不包括我添加的错误函数)所以你可以看到问题。

谢谢!

您正在将 URL 从一个字符串修改为另一个字符串 - 系统如何知道第二个字符串是否会导致错误?

可以做的是重新定义 onload and onerror handlers of that particular image, as in this example,以及将以前的 URL 值保存到该 img 的属性中。然后,如果触发错误条件,您将清除 onload 和 onerror 以及 re-set 先前的 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.'));
})

对于我的方法,我使用 ajax 检查新图像 URL 是否有效(没有 return 任何错误代码)并且只更改 URL如果 ajax 调用成功。

$(".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
    }
  });

});

(Fiddle: https://jsfiddle.net/48hpeo9z/7/)

但是因为 Tumblr 包含图像的原始宽度及其 <figure> 标签,您还可以使用它来检查是否存在更大版本的图像。