在鼠标悬停按钮上:测试外部图像 URL 是否存在,如果是,则显示图像,如果不显示 noimg.png



我有一个鼠标悬停区域,通过jquery弹出图像。我想测试外部图像是否存在。如果是,请照常显示,如果不是仅显示noimg.png。

我的代码:

 var image = new Image(); 
 image.src = urllink;
 var imagewidth = image.width;
 if (imagewidth == 0) {
   $('#cardpicture').attr('src', ".../noimg.png");
  } else
    {
       $('#cardpicture').attr('src', urllink);
    }

它似乎仅适用于第二次鼠标悬停。所以检查是正确的,但我必须在"鼠标悬停"区域中移动鼠标两次才能显示图片(如果存在(。在第一个"鼠标悬停"事件中,它始终显示noimg.png。我做错了什么?

我刚刚尝试了使用 .ajax 和 head 方法,但发现它只会给出错误,因为图片是外部图片(不位于我的服务器上(。

我只能想象这可能与外部图片的"加载延迟"有关。

提前问候和感谢!

如果有人对解决方案感兴趣...我终于找到了:

// test if image exists --------------:
loadImage(urllink);
function loadImage(src) {
    var image = new Image();
    image.onload = function() {
        if ('naturalHeight' in this) {
            if (this.naturalHeight + this.naturalWidth === 0) {
                this.onerror();
                return;
            }
        } else if (this.width + this.height == 0) {
            this.onerror();
            return;
        }
        // At this point, there's no error. Picture is available:
        $('#picture').attr('src', urllink);
        $('.image-content').css("display", "flex");
    };
    image.onerror = function() {
        //display noimg.png
        $('#picture').attr('src', ".../noimg.png");
        $('.image-content').css("display", "flex");
    };
    image.src = src;
}

最新更新