Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 仅当新背景图像退出时才更改背景图像_Javascript_Html_Css - Fatal编程技术网

Javascript 仅当新背景图像退出时才更改背景图像

Javascript 仅当新背景图像退出时才更改背景图像,javascript,html,css,Javascript,Html,Css,但是,当图像不存在时会出现问题。我如何才能这样做,添加real类名,并仅在图像存在时更改URL,而不是在其他情况下 我想发出一个AJAX请求,看看它是否成功,然后设置类名和URL,如果成功的话,但是我想知道是否有更好的方法 下面是一个使用jQuery的示例 我认为您应该创建一个新的图像元素,将其附加到DOM并侦听事件: var image = document.getElementById('image'); image.className += ' real'; image.style.bac

但是,当图像不存在时会出现问题。我如何才能这样做,添加
real
类名,并仅在图像存在时更改URL,而不是在其他情况下

我想发出一个AJAX请求,看看它是否成功,然后设置类名和URL,如果成功的话,但是我想知道是否有更好的方法

下面是一个使用jQuery的示例 我认为您应该创建一个新的图像元素,将其附加到DOM并侦听事件:

var image = document.getElementById('image');
image.className += ' real';
image.style.backgroundImage = 'url(http://www.example.com/real.png)';
var image=$('');
image.on(“加载”,函数(){
//在这里添加类
invisibleContainer.remove();
控制台日志(“已加载”);
});
image.on(“错误”,函数(){
//如果图像丢失,请执行某些操作
console.log(“图像丢失”);
});
变量invisibleContainer=$('');
css(“显示”、“无”);
$('body').append(invisibleContainer);
JSFIDLE

下面是一个使用本机JavaScript的示例 在将图像应用为背景之前,需要检查图像是否存在(可以加载)

该问题以前由以下人员解决:

它提供了一个本地JavaScript方法来检查图像是否存在

代码可能如下所示:

var image = $('<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/36/Hopetoun_falls.jpg/300px-Hopetoun_falls.jpg" />');
image.on("load", function() {
    // add the class here
    invisibleContainer.remove();
    console.log("loaded");
});
image.on("error", function() {
    // do something if the image is missing
    console.log("image is missing");
});
var invisibleContainer = $('<div></div>');
invisibleContainer.css("display", "none");
$('body').append(invisibleContainer);
评论 我不确定加载映像的服务器开销是否比发出AJAX请求的服务器开销小。也许其他人可以评论

var image = $('<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/36/Hopetoun_falls.jpg/300px-Hopetoun_falls.jpg" />');
image.on("load", function() {
    // add the class here
    invisibleContainer.remove();
    console.log("loaded");
});
image.on("error", function() {
    // do something if the image is missing
    console.log("image is missing");
});
var invisibleContainer = $('<div></div>');
invisibleContainer.css("display", "none");
$('body').append(invisibleContainer);
var image = document.getElementById('image');
image.src = "http://www.example.com/real.png";

image.onerror = function( ) {
    /* do some appropriate action... */
}​​​​​​​​​​​​​​​​​
img.onload = function( ) {
    image.className += ' real';
    image.style.backgroundImage = 'url(http://www.example.com/real.png)';
}