HTML alt 属性在 img 元素中使用,用于提供图像的文本描述,如果图像无法加载,则会显示该描述。
如果正确使用 alt 属性,每个人都可以理解网站上图像的信息和上下文,包括残障人士或互联网连接速度较慢的人。它对于搜索引擎优化、包容性设计和 Web 可访问性至关重要。
语法
<tag alt = "value"></tag>
适用于
下面列出的元素允许使用 HTML alt 属性。
元素 | 描述 |
---|---|
<img> | HTML <img> 标签用于在文档中附加图像 |
<area> | HTML 中的 HTML<area>元素用于定义图像映射中的可点击区域。 |
<input> | HTML 中的 HTML <input>元素用于输入文本。 |
HTML alt 属性的示例
以下代码描述了 alt 属性的各种使用方式。
带有 img 元素的 Alt 属性
下面的代码显示了 alt 属性如何与 img 标签一起使用。在第一种情况下,图像显示没有任何错误,但在第二种情况下,由于在指定位置找不到图像,因此会显示替代文本。
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML 'alt' attribute</title>
<style>
img {
width: 300px;
height: 100px;
}
</style>
</head>
<body>
<!--HTML 'alt' attribute-->
<p>Example of the HTML 'alt' attribute</p>
<p>Image without any error</p>
<img src="https://www.qikepu.com/images/logo.png?v3"
alt="QikepuCom logo">
<br>
<p>Images with error</p>
<img src="Asset-2PP_.png"
alt="QikepuCom logo">
</body>
</html>
带有 input 元素的 Alt 属性
考虑到另一种情况,我们将使用 alt 属性和输入 type=image。
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML 'alt' attribute</title>
<style>
img {
width: 300px;
height: 50px;
}
</style>
</head>
<body>
<!--HTML 'alt' attribute-->
<p>Example of the HTML 'alt' attribute</p>
<p>Image with an error</p>
<input type="image"
src="download1.png"
alt="QikepuCom old logo">
<p>Image without any error</p>
<input type="image"
src="https://www.qikepu.com/images/logo.png?v3"
alt="QikepuCom logo">
</body>
</html>
带有 area 元素的 Alt 属性
让我们看一下以下示例,我们将在其中将 alt 属性与 area 标签一起使用。下面的代码将生成一个输出,其中包含网页上显示的图像。当用户单击图像时,它会显示其替代文本。
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML 'alt' attribute</title>
</head>
<body>
<!--HTML 'alt' attribute-->
<p>Example of the HTML 'alt' attribute</p>
<!--<img src="images (1).png"
usemap="#sep"
width = "400"
height="379">-->
<img src="images (1).png"
alt="HTML CSS JS logo"
usemap="#sep"
width="200"
height="200">
<map name="sep">
<area shape="circle"
coords="30,44,270,350"
alt="HTML logo"
href="html logo.html">
</map>
</body>
</html>
HTML logo.html文件代码
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML</title>
</head>
<body>
<img src="html log.jpg" alt="HTML logo">
</body>
</html>
支持的浏览器
浏览器 | ![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|---|
是否支持 | Yes | Yes | Yes | Yes | Yes |