【问题标题】:on mouseover button: Test if external image url exists, if yes show image, if not show noimg.png在鼠标悬停按钮上:测试是否存在外部图像 url,如果存在则显示图像,如果不存在则显示 noimg.png
【发布时间】:2019-08-21 03:25:13
【问题描述】:

我有一个鼠标悬停区域,通过 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 方法,但发现它只会报错,因为图片是外部图片(而不是位于我的服务器上)。

我只是可以想象它可能与外部图片的“加载延迟”有关。

提前致以最诚挚的问候和感谢!

【问题讨论】:

标签: javascript jquery image


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-03-16
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 2015-07-31
    • 2013-05-27
    • 1970-01-01
    • 2015-07-17
    • 2021-07-05
    相关资源
    最近更新 更多