我有一个网页,里面有很多图片。有时映像不可用,因此在客户机的浏览器中显示一个损坏的映像。
我如何使用jQuery来获取图像集,过滤它到破碎的图像,然后替换src?
—我本以为用jQuery会更容易做到这一点,但事实证明使用纯JavaScript解决方案更容易,也就是Prestaul提供的解决方案。
我有一个网页,里面有很多图片。有时映像不可用,因此在客户机的浏览器中显示一个损坏的映像。
我如何使用jQuery来获取图像集,过滤它到破碎的图像,然后替换src?
—我本以为用jQuery会更容易做到这一点,但事实证明使用纯JavaScript解决方案更容易,也就是Prestaul提供的解决方案。
当前回答
多年来,这一直困扰着我。我的CSS修复在img上设置了一个背景图像。当动态图像src没有加载到前景时,img的bg上有一个占位符。如果你的图片有一个默认大小(例如高度,最小高度,宽度和/或最小宽度),这是有效的。
你会看到破碎的图像图标,但这是一种改进。成功测试到IE9。iOS、Safari和Chrome甚至都不会显示坏掉的图标。
.dynamicContainer img {
background: url('/images/placeholder.png');
background-size: contain;
}
添加一个小动画,让src在没有背景闪烁的情况下加载。Chrome浏览器在后台可以平滑淡出,但桌面版Safari浏览器却不能。
.dynamicContainer img {
background: url('/images/placeholder.png');
background-size: contain;
animation: fadein 1s;
}
@keyframes fadein {
0% { opacity: 0.0; }
50% { opacity: 0.5; }
100% { opacity: 1.0; }
}
.dynamicContainer img { background: url('https://picsum.photos/id/237/200'); background-size: contain; animation: fadein 1s; } @keyframes fadein { 0% { opacity: 0.0; } 50% { opacity: 0.5; } 100% { opacity: 1.0; } } img { /* must define dimensions */ width: 200px; height: 200px; min-width: 200px; min-height: 200px; /* hides broken text */ color: transparent; /* optional css below here */ display: block; border: .2em solid black; border-radius: 1em; margin: 1em; } <div class="dynamicContainer"> <img src="https://picsum.photos/200" alt="Found image" /> <img src="https://picsumx.photos/200" alt="Not found image" /> </div>
其他回答
对于React开发者:
<img
src={"https://urlto/yourimage.png"} // <--- If this image src fail to load, onError function will be called, where you can add placeholder image or any image you want to load
width={200}
alt={"Image"}
onError={(event) => {
event.target.onerror = "";
event.target.src = "anyplaceholderimageUrlorPath"
return true;
}}
/>
我也有同样的问题。这个代码在我的案子上很有效。
// Replace broken images by a default img
$('img').each(function(){
if($(this).attr('src') === ''){
this.src = '/default_feature_image.png';
}
});
更好的呼叫使用
jQuery(window).load(function(){
$.imgReload();
});
因为使用文档。ready并不一定意味着图像被加载,只是HTML。因此,不需要延迟调用。
(window.jQuery || window.Zepto).fn.fallback = function (fallback) {
return this.one('error', function () {
var self = this;
this.src = (fallback || 'http://lorempixel.com/$width/$height').replace(
/\$(\w+)/g, function (m, t) { return self[t] || ''; }
);
});
};
你可以传递一个占位符路径,并通过$*访问失败图像对象的所有属性:
$('img').fallback('http://dummyimage.com/$widthx$height&text=$src');
http://jsfiddle.net/ARTsinn/Cu4Zn/
你可以使用GitHub自己的fetch:
前端:https://github.com/github/fetch 或者在后端,一个Node.js版本:https://github.com/bitinn/node-fetch
fetch(url)
.then(function(res) {
if (res.status == '200') {
return image;
} else {
return placeholder;
}
}
编辑:这个方法将取代XHR,据说已经在Chrome。对于将来阅读这篇文章的人来说,您可能不需要包含上述库。