我有一个网页,里面有很多图片。有时映像不可用,因此在客户机的浏览器中显示一个损坏的映像。
我如何使用jQuery来获取图像集,过滤它到破碎的图像,然后替换src?
—我本以为用jQuery会更容易做到这一点,但事实证明使用纯JavaScript解决方案更容易,也就是Prestaul提供的解决方案。
我有一个网页,里面有很多图片。有时映像不可用,因此在客户机的浏览器中显示一个损坏的映像。
我如何使用jQuery来获取图像集,过滤它到破碎的图像,然后替换src?
—我本以为用jQuery会更容易做到这一点,但事实证明使用纯JavaScript解决方案更容易,也就是Prestaul提供的解决方案。
当前回答
纯粹的JS。 我的任务是:如果图像'bl-once.png'是空的->插入第一个(没有404状态)图像从数组列表(在当前目录):
<img src=“http://localhost:63342/GetImage/bl-once.png” width=“200” onerror=“replaceEmptyImage.insertImg(this)”>
也许它需要改进,但是:
var srcToInsertArr = ['empty1.png', 'empty2.png', 'needed.png', 'notActual.png']; // try to insert one by one img from this array var path; var imgNotFounded = true; // to mark when success var replaceEmptyImage = { insertImg: function (elem) { if (srcToInsertArr.length == 0) { // if there are no more src to try return return "no-image.png"; } if(!/undefined/.test(elem.src)) { // remember path path = elem.src.split("/").slice(0, -1).join("/"); // "http://localhost:63342/GetImage" } var url = path + "/" + srcToInsertArr[0]; srcToInsertArr.splice(0, 1); // tried 1 src if(imgNotFounded){ // while not success replaceEmptyImage.getImg(url, path, elem); // CALL GET IMAGE } }, getImg: function (src, path, elem) { // GET IMAGE if (src && path && elem) { // src = "http://localhost:63342/GetImage/needed.png" var pathArr = src.split("/"); // ["http:", "", "localhost:63342", "GetImage", "needed.png"] var name = pathArr[pathArr.length - 1]; // "needed.png" xhr = new XMLHttpRequest(); xhr.open('GET', src, true); xhr.send(); xhr.onreadystatechange = function () { if (xhr.status == 200) { elem.src = src; // insert correct src imgNotFounded = false; // mark success } else { console.log(name + " doesn't exist!"); elem.onerror(); } } } } };
因此,它将插入正确的'needed.png'到我的src或'no-image.png'从当前目录。
其他回答
我创建了一个小提琴来取代破碎的图像使用"onerror"事件。 这可能对你有帮助。
//the placeholder image url
var defaultUrl = "url('https://sadasd/image02.png')";
$('div').each(function(index, item) {
var currentUrl = $(item).css("background-image").replace(/^url\(['"](.+)['"]\)/, '$1');
$('<img>', {
src: currentUrl
}).on("error", function(e) {
$this = $(this);
$this.css({
"background-image": defaultUrl
})
e.target.remove()
}.bind(this))
})
这是一个快速和肮脏的方法来替换所有破碎的图像,没有必要改变HTML代码;)
codepen例子
$("img").each(function(){
var img = $(this);
var image = new Image();
image.src = $(img).attr("src");
var no_image = "https://dummyimage.com/100x100/7080b5/000000&text=No+image";
if (image.naturalWidth == 0 || image.readyState == 'uninitialized'){
$(img).unbind("error").attr("src", no_image).css({
height: $(img).css("height"),
width: $(img).css("width"),
});
}
});
$(window).bind('load', function() {
$('img').each(function() {
if( (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0)
|| this.readyState == 'uninitialized' ) {
$(this).attr('src', 'missing.jpg');
}
});
});
来源:http://www.developria.com/2009/03/jquery-quickie--broken-images.html
对于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;
}}
/>
我相信这就是你想要的:jQuery。预加载
下面是演示中的示例代码,你指定加载和未找到的图像,你就全部设置好了:
jQuery('#images img').preload({
placeholder:'placeholder.jpg',
notFound:'notfound.jpg'
});