Javascript 使用javascript检查图像是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14651348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:31:10  来源:igfitidea点击:

Checking if image does exists using javascript

javascript

提问by X10nD

Possible Duplicate:
Check if image exists with given url using jquery
Change image source if file exists

可能的重复:
使用 jquery 检查给定 url 的
图像是否存在如果文件存在则更改图像源

I am throwing the value of an image path from a textbox into boxvalue and want to validate if the image exist using javascript.

我将文本框中的图像路径的值扔到 boxvalue 中,并想使用 javascript 验证图像是否存在。

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

I browsed stackoverflow and found the below to get the image width/height, but don't want to use this.

我浏览了 stackoverflow 并找到了以下内容来获取图像宽度/高度,但不想使用它。

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

How can an I validate if it is really an image from the image path?

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

回答by maerics

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

回答by Felipe Oriani

You can create a function and check the completeproperty.

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

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

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

    return true;
}

and call this funciton

并调用这个函数

 var exists = ImageExists('#UrlQueueBox');

Same function with the url instead of a selector as parameter (your case):

使用 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;
}