简体   繁体   English

html中图像标记的alt属性

[英]alt attribute for Image tag in html

Scenario: 场景:

 <img src="filepath" alt="image not found">

This will make sure that if the file is not found in the path then the text would be loaded ..... 这将确保如果在路径中找不到该文件,那么将加载文本.....

Question: Instead of a alternative text can a image be loaded ?? 问题:可以加载图像而不是替代文本吗? is there any tags would readily serve my purpose and is there any custom javascript functions which could be given in #alt tag?? 有没有任何标签可以满足我的目的,是否有任何自定义的JavaScript函数,可以在#alt标签?

You can check if the image loaded in JavaScript: 您可以检查JavaScript中加载的图像是否:

var img = document.getElementById('image');
if ( img.complete && img.naturalWidth == 0 ) {
  // some error, load alternate image:
  img.src = "path to alternative img";
}

Edit: Complete solution (using onerror from @JoDev's answer) would be: 编辑:完整的解决方案(使用来自@ JoDev的答案的onerror )将是:

<script>
function validate (img) {
  // Clear the callback to avoid infinite loop in case
  // new image path would be also invalid.
  img.onerror = null;

  if ( img.complete && img.naturalWidth == 0 ) {
    // some error, load alternate image:
    img.src = "http://example.com/valid_path.png";
  }
}
</script>

<img onerror="javascript:validate(this);" 
     src="http://example.com/some_invalid_path.png"/>

There is a special event wich allow you to make this. 有一个特殊的事件可以让你做到这一点。 It's : 它的 :

<img src="" onerror="this.src='path/to/default'" />

Please refer below code.. 请参考以下代码..

Inside onerror function add src path which you want load. 在onerror函数内添加你想要加载的src路径。 If src is image is loaded. 如果src是图像加载。

<img onerror="this.onerror=null;this.src='http://www.personal.psu.edu/oeo5025/jpg.jpg'" id="ddd" 
src='http://www.loveimagesdownload.com/wp-content/uploads/2016/08/declaration-of-love_23-2147517078.jpg'/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM