在将图像添加为背景图像之前检查图像是否存在 [英] Checking if an image exists before adding it as a background image
问题描述
关于在图像上使用 .error() 来确定它们是否存在以及如果不存在则添加占位符的堆栈上有一些解决方案,但它们都严格地在 标签.有没有人对没有添加到
<img>
标签而是作为 div 背景的图像执行这种类型的验证?
There are a few solutions on stack regarding the use of .error() on images to determine if they exist and adding placeholders if they don't, but they all discuss its use strictly on <img>
tags. Has anyone performed this type of validation to images that are not being added to <img>
tags but rather as backgrounds on divs?
我们有一组来自第 3 方 API 的图像,并且在某些情况下,返回的整个图像 URL 集不存在.验证一组图像(注定是背景图像)以确定它们是否存在,然后在验证失败时应用适当的占位符的正确方法是什么?
We have a set of images coming in from a 3rd party API and there are cases where the entire set of image urls' that are returned do not exist. What would be the proper method in validating a set of images (destined to be background images) to determine if they exist and then apply proper placeholders if the validation(s) fails?
推荐答案
有几种方法可以做到:
使用ajax:
$.ajax({
url: "image.jpg",
type: "HEAD",
error: function () { alert("no image"); }
});
使用 javascript 图像对象:
Using the javascript image object:
var image = new Image();
image.src = "image.jpg";
if (image.width == 0) {
alert("no image");
}
这篇关于在将图像添加为背景图像之前检查图像是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!