gpt4 book ai didi

javascript - 如果背景图像 url 是 404 那么 jquery

转载 作者:行者123 更新时间:2023-12-01 05:51:42 25 4
gpt4 key购买 nike

我使用以下代码将背景图像缩略图设置为嵌入式 YouTube 视频的占位符。如果视频被删除,缩略图将成为 YouTube 的默认 404 缩略图。我想设置自己的 404 缩略图,但不知道如何设置。我可以找到检查 img 错误的方法,但不能检查背景图像错误。 (另外,我无法查找没有背景图像的 div,因为它们都有一个,它可能只是一个损坏的链接。)

有人知道如何检查损坏的背景图像网址吗?

$(function(){ 

// VIDEO LOAD

var videoLinks = {};

function clickVideo() {
// trim off img-
var postId = $(this).attr("id").substr(4);
if (videoLinks[postId]) {
$("#" + postId).html(videoLinks[postId]);
}
}

function storeVideo() {
var videoDiv = this;
var postId = $(videoDiv).attr("id");
var code = $(videoDiv).attr("videohtml");
$(videoDiv).removeClass("videoNoThumbnail");
var re = new RegExp("(.*/embed/([a-zA-Z0-9_-]+)\\?)(.*)", "m");
var match = code.match(re);

if (match) {
code = match[1] + "autoplay=1&" + match[3];
var videoId = match[2];
var div = $("<div class=videoThumbnail />");
div.css("background-image",
"url('http://img.youtube.com/vi/" + videoId + "/0.jpg')");



var img = $("<img src=http://dinakelberman.com/play.png class=playButton />");
img.attr("id", "img-" + postId);
img.click(clickVideo);
div.append(img);
// two.empty();
$(videoDiv).append(div);
}
videoLinks[postId] = code;

}

function updateVideos() {
$('div.videoNoThumbnail').each(storeVideo);

setTimeout(updateVideos, 200);
}

updateVideos();

})

最佳答案

这可以通过使用 ajax 请求加载缩略图来完成:当 Youtube 提供 404 缩略图时,它实际上会响应 404 状态。

$.get('http://img.youtube.com/vi/' + videoId + '/0.jpg')
.success(function(d){
// video not removed: set thumbnail
div.css("background-image","url('http://img.youtube.com/vi/" + videoId + "/0.jpg')");
})
.error(function(d){
// video removed: set your own thumbnail
});

成功的案例可以进一步调整:我编写的代码加载相同的图像两次(首先使用ajax请求,然后在设置背景图像时加载)。您实际上可以使用通过 ajax 请求加载的图像,将响应数据转换为 data-uri image background

但是,要执行此操作,您需要使用 binary transport 请求图像。对于 jQuery(或使用标准 XMLHttpRequest )并将数据转换为 base64。

关于javascript - 如果背景图像 url 是 404 那么 jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21507116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com