使用javascript检查图像是否存在

X10*_*0nD 19 javascript

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

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

 var boxvalue = $('#UrlQueueBox').val();
Run Code Online (Sandbox Code Playgroud)

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

var img = document.getElementById('imageid'); 
Run Code Online (Sandbox Code Playgroud)

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

mae*_*ics 63

// 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);
});
Run Code Online (Sandbox Code Playgroud)

  • 此测试创建一个新图像,该图像保存在 Google Chrome 浏览器中的 Resources --> Images 下,无论 url 是否为我特别不喜欢的有效图像。 (2认同)
  • 这很好,但是你能让它返回 URL 吗?我有一个尝试加载列表图标的循环,我需要一些可以返回您尝试过的 URL 或如果图像不存在的默认 URL 的东西。所有的解决方案似乎都运行了一些代码或转储到控制台。 (2认同)

Fel*_*ani 5

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

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

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

    return true;
}
Run Code Online (Sandbox Code Playgroud)

并称之为这个功能

 var exists = ImageExists('#UrlQueueBox');
Run Code Online (Sandbox Code Playgroud)

与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;
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

48751 次

最近记录:

8 年,10 月 前