spe*_*z86 5 api jquery background-image
关于在图像上使用.error()以确定它们是否存在以及如果不存在则添加占位符,堆栈上有一些解决方案,但它们都严格讨论它在<img>标签上的使用.有没有人对未添加到<img>标签但是作为div背景的图像执行此类验证?
我们有一组来自第三方API的图像,并且有些情况下返回的整个图像网址都不存在.验证一组图像(目的地是背景图像)以确定它们是否存在然后在验证失败时应用适当的占位符的正确方法是什么?
lol*_*lol 23
有几种方法可以做到这一点:
使用ajax:
$.ajax({
url: "image.jpg",
type: "HEAD",
error: function () { alert("no image"); }
});
Run Code Online (Sandbox Code Playgroud)
使用javascript图像对象:
var image = new Image();
image.src = "image.jpg";
if (image.width == 0) {
alert("no image");
}
Run Code Online (Sandbox Code Playgroud)