【问题标题】:how to check if link directs to an existing image javascript如何检查链接是否指向现有图像 javascript
【发布时间】:2020-05-28 17:11:08
【问题描述】:

我想知道链接是否重定向到 javascript 中的实际现有图像,因为我不希望发生以下情况:

<img src="http://idontexist.lol/fakeimg.png" alt="non existant image" width="400">

【问题讨论】:

  • 对图片使用onload函数来确保图片是否存在
  • 你可以尝试点击 URL 看看它是否给出 404

标签: javascript image exists


【解决方案1】:

onload()函数用于检测图片在url中是否有效。如果输入onload函数则为有效图片url

function test(event,val){
   console.log("image"+val+" is loaded");
   event.style.display="block";
}
<img src="http://idontexist.lol/fakeimg.png"onload="test(this,1)" alt="non existant image"style="display:none" width="400">
<img src="https://cdn.sstatic.net/Img/unified/sprites.svg?v=fcc0ea44ba27g"onload="test(this,2)"style="display:none" alt="non existant image" width="400">

【讨论】:

    猜你喜欢
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多