<style>
.image {
width: 136px;
height: 23px;
background-color: red;
background-image: url(placeholder.png);
background-repeat: no-repeat;
background-position: center;
background-size: auto 100%;
}
.image.real {
background-color: blue;
}
</style>
<div id="image" class="image"></div>
在上面的布局中,我想从URL获取另一个图像,并在获取图像后,将另一个类添加到div并将其背景图像URL设置为此新URL。类似的东西:
var image = document.getElementById('image');
image.className += ' real';
image.style.backgroundImage = 'url(http://www.example.com/real.png)';
但是,图像不存在时会出现问题。如何执行此类操作并添加real
类名称并仅在图像存在时更改URL,否则不会更改?
我正在考虑制作一个AJAX请求以查看它是否成功,然后设置类名和URL,如果是这样,但我想知道是否有更好的方法。
答案 0 :(得分:1)
我认为你应该创建一个新的图像元素,将它附加到DOM并监听事件:
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);
JSfiddle http://jsfiddle.net/qkXZ4/
答案 1 :(得分:1)
在将图像用作背景之前,您需要检查图像是否存在(可以加载)。
此问题之前已通过以下方式解决:
javascript check image existence
提供了一种用于检查图像是否存在的本机JavaScript方法。
代码可能如下所示:
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)';
}
我不确定加载图像的服务器开销是否小于与发出AJAX请求相关的服务器开销。也许其他人可以评论。