Jquery 如何修改img src,除非结果破坏了图像url
我有一个为Tumblr设计的脚本,它修改了内联图像中的部分img src(在文本/标题/等文章中,而不是照片/照片集文章中),以显示更大的图像,因为加载到Tumblr中的默认url强制它们为500px或更小,并且许多图像通常更大,可以拉伸以填充其容器。然而,有时较大图像的url并不总是可用的,我想知道如果更改url会破坏脚本,是否有办法取消该特定图像上的脚本。这是我所拥有的,但它在页面上闪烁:Jquery 如何修改img src,除非结果破坏了图像url,jquery,image,src,Jquery,Image,Src,我有一个为Tumblr设计的脚本,它修改了内联图像中的部分img src(在文本/标题/等文章中,而不是照片/照片集文章中),以显示更大的图像,因为加载到Tumblr中的默认url强制它们为500px或更小,并且许多图像通常更大,可以拉伸以填充其容器。然而,有时较大图像的url并不总是可用的,我想知道如果更改url会破坏脚本,是否有办法取消该特定图像上的脚本。这是我所拥有的,但它在页面上闪烁: $( window ).on( "load", function(){ $('.tmblr-full
$( 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.'))
})
});
使用原始代码(不包括我添加的错误函数),以便您可以看到问题
谢谢大家! 您正在将URL从一个字符串修改为另一个字符串-系统如何知道第二个字符串是否会导致错误 您可以做的是重新定义,以及将以前的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.'));
})
对于我的方法,我使用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
}
});
});
(小提琴:)
但是由于Tumblr包含图像的原始宽度及其
标记,您也可以使用它来检查图像是否存在更大的版本。如果图像不存在,tumbler会返回什么url?@TonyHensler它不会返回任何内容,图像会简单地中断。我对Javascript知之甚少,甚至一无所知,不幸地我将如何将其合并到现有脚本中,或者重新编写?非常感谢你!对不起,最后一行是$img而不是img。明天我将在电脑上更正它。我测试了脚本,但它不起作用:(你可以在这里看到: