使用Javascript我可以通过更改src
参数来替换图片,例如
document.getElementById('image-id').src = 'new-image.png';
如果我需要动态更改图片,且只有新图片可用且有效,我是否需要调整上述代码才能在浏览器能够获取图片时执行替换?
换句话说,如果new-image.png
的HTTP请求以错误(403,404,500,...)结束,或者文件不是有效图片,我想要保留原始图像并且不执行代码,否则浏览器不显示图像。
答案 0 :(得分:3)
您可以单独加载图像并在成功时将其交换:
var img = document.createElement('img');
img.onload = function() {
// It worked, either replace `image-id` with this new `img` element:
var oldImg = document.getElementById("image-id");
oldImg.parentNode.insertBefore(img, oldImg);
oldImg.parentNode.removeChild(oldImg);
img.id = "image-id";
// ===OR===
// Just set `image-id`'s `src` (it'll come from cache, presumably)
document.getElementById("image-id").src = img.src;
img = img.onload = null;
};
img.src = "new-image.png"; // Important to do this AFTER hooking `onload` above
答案 1 :(得分:0)
试试这个:
使用Javascript:
function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}
if(imageExists('new-image.png'))//when image exists
document.getElementById('image-id').src = 'new-image.png';
使用Jquery:
var image_url='new-image.png';
$.get(image_url)
.done(function() {
document.getElementById('image-id').src = 'new-image.png';
}).fail(function() {
// Image doesn't exist
})
<强> Reference 强>
答案 2 :(得分:0)
// The "callback" argument is called with either true or false
// depending on whether the image at "url" exists or not.
function imageExists(url, callback) {
var img = new Image();
img.onload = function() { callback(true); };
img.onerror = function() { callback(false); };
img.src = url;
}
// Sample usage
var imageUrl = 'http://www.google.com/images/srpr/nav_logo14.png';
imageExists(imageUrl, function(exists) {
console.log('RESULT: url=' + imageUrl + ', exists=' + exists);
});
答案 3 :(得分:0)
如:How do I check if file exists in jQuery or JavaScript?
中所述对该文件执行ajax请求(这是使用jquery完成的)
$.ajax({
url: 'http://www.example.com/somefile.ext',
type: 'HEAD',
error: function()
{
// file does not exist
},
success: function()
{
// file exists
}
});
答案 4 :(得分:0)
使用jQuery,您可以使用:
function checkImage(img, src) {
$("<img/>").one('load', function () {
img.src = src;
}).attr('src',src);
}
像这样使用:
checkImage(document.getElementById('image-id'), 'new-image.png');
答案 5 :(得分:0)
常见解决方案:
$("<img/>")
.load(function() {
document.getElementById('image-id').src = 'new-image.png';
})
.attr('src', 'new-image.png');
清洁解决方案:
$("<img/>")
.load(function() {
document.getElementById('image-id').src = 'new-image.png';
$(this).remove();
})
.error(function() {
$(this).remove();
})
.attr('src', 'new-image.png');