【问题标题】:how to modify img src unless the result breaks the image url除非结果破坏了图像 url,否则如何修改 img src
【发布时间】:2017-02-02 22:42:43
【问题描述】:

我有一个为 Tumblr 设计的脚本,它会修改内联图像(在文本/标题/等帖子中,而不是照片/照片集帖子中)中的部分 img src 以显示更大,作为加载到的默认 url Tumblr 强制它们为 500 像素或更小,并且许多图像通常更大并且可以拉伸以填充它们的容器。但是,有时较大图像的 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与原代码(不包括我添加的错误函数)这样你就可以看到问题了。

谢谢!

【问题讨论】:

  • 图片不退出,tumbler返回什么url?
  • @TonyHensler 它没有返回任何东西,图像只是破坏了。

标签: jquery image src


【解决方案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> 标签,您也可以使用它来检查是否存在更大版本的图像。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 不幸的是,我对 Javascript 知之甚少。我如何将其合并到现有脚本中,或重新编写?非常感谢!
    • 对不起,最后一行是 $ img 而不是 img。我明天会在我的电脑上更正它。
    • 我测试了脚本,但它不起作用。 :( 你可以在这里看到:jsfiddle.net/jeongguk/48hpeo9z/3
    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 2021-01-31
    相关资源
    最近更新 更多