如何通过单击按钮向显示的图片添加替代文本?

时间:2013-05-16 09:06:26

标签: javascript html

是否有办法在图片无法显示的情况下添加单独的替代文字(例如“图片1/2不可用”)?如何更改此代码以实现此目的?

(Sridhar的代码)

<script type = "text/javascript">
        function pic1()
        {
            document.getElementById("img").src = "picture 1 source";
        }
        function pic2()
        {
            document.getElementById("img").src ="picture 2 source";
        } 
</script>

<img src = "" id = "img"/> <input type="button" value="Show Picture
    1" onclick="pic1()"/> <input type="button" value="Show Picture 2"
    onclick="pic2()"/>

2 个答案:

答案 0 :(得分:4)

  

有没有办法添加单独的替代文字(例如“图片1/2   不可用“)以防图片无法显示?

是的,这就是alt属性的用途 - 它实际上是图像的必需属性。

您可以使用.alt设置图片的alt标记,如下所示:

var image = document.getElementById("img");
image.src = "Image src here"
image.alt = "Image alt here - if image failed to render, you will see this!"

假设您必须通过JavaScript执行此操作。大多数人只是将它包含在HTML本身中:

<img src = "" id = "img" alt="Alternative text here!"/>

详细了解alt属性here


修改:您可以考虑使用onerror关于Derek的观点:

  

“仅在找不到图像时,onerror允许使用不同的替代文字   渲染时或未找到图像时“

答案 1 :(得分:3)

是的,有办法。将onerror属性与错误文本或替代图像的路径一起使用。

<img onerror="this.src='/path/to/alternate/img.jpg'" src="/your/img.jpg">

<img onerror="this.alt='picture 1/2 not available'" src="/your/img.jpg">

编辑当然,正如Zenith指出的那样,你应该在每张图片上使用(必需的)alt属性。使用onerror假设您想要向用户显示不同的内容,如果找不到图像,而不是用户使用屏幕阅读器或以其他方式选择禁用图像。另一种方法是显示原始alt文本,并附加“不可用”消息:

<img alt="picture 1/2" onerror="this.alt=this.alt+': not available'" src="/your/img.jpg">

Demo

相关问题