使用javascript检查图像是否存在

时间:2013-02-01 17:01:18

标签: javascript

  

可能重复:
  Check if image exists with given url using jquery
  Change image source if file exists

我将图像路径的值从文本框中抛出到boxvalue,并希望使用javascript验证图像是否存在。

 var boxvalue = $('#UrlQueueBox').val();

我浏览了stackoverflow并找到了下面的图片宽度/高度,但不想使用它。

var img = document.getElementById('imageid'); 

我如何验证它是否真的是来自图像路径的图像?

2 个答案:

答案 0 :(得分:61)

// 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);
});

答案 1 :(得分:5)

您可以创建一个函数并检查complete属性。

function ImageExists(selector) {
    var imageFound = $(selector); 

    if (!imageFound.get(0).complete) {
        return false;
    }
    else if (imageFound.height() === 0) {
        return false;
    }

    return true;
}

并调用此函数

 var exists = ImageExists('#UrlQueueBox');

与url相同的函数而不是选择器作为参数(你的情况):

function imageExists(url){

    var image = new Image();

    image.src = url;

    if (!image.complete) {
        return false;
    }
    else if (image.height === 0) {
        return false;
    }

    return true;
}