img
元素允许您将图像嵌入到HTML文档中。
它有局部属性: src,alt,height,width,usemap,ismap
。
HTML5中的border,longdesc,name,align,hspace
和 vspace
属性已过时。
要嵌入图像,您需要使用 src
和 alt
属性,如下所示。
<!DOCTYPE HTML>
<html>
<body>
<img src="http://www.www.juanshu.me/style/download.png"
alt="Triathlon Image"
width="200"
height="67" />
</body>
</html>
src
属性指定图像的URL。
如果无法显示图片,则 alt
属性定义内容。
width
和 height
属性设置图像大小(以像素为单位)。
img
元素的常见用途是结合 a
元素创建基于图像的超链接。
以下代码显示了如何使用 img
和 a
元素。
<!DOCTYPE HTML>
<html>
<body>
<p>
<a href="//www.juanshu.me/page.html">
<img ismap src="http://www.www.juanshu.me/style/download.png"/>
</a>
</p>
</body>
</html>
如果将 ismap
属性应用于 img
元素,则可以创建服务器端图像映射,这意味着您在图像上单击的位置将附加到URL。
例如,如果您从图像的顶部点击了4个像素,从左边缘点击了10个像素,浏览器将导航到以下内容:
//www.juanshu.me/page.html?10,4
您可以创建客户端图像映射:单击图像中的不同区域会导致浏览器导航到不同的URL。
客户端图像映射的关键元素是 map
与局部属性 name
。
如果使用 id
属性,它必须具有与 name
属性相同的值。
map
元素可以有一个或多个 area
元素。
每个区域元素标记图像中可以点击的区域。
area
元素具有局部属性: alt,href,target,rel,media,hreflang,type,shape,coords
。
rel,media和hreflang属性是HTML5中的新特性。nohref属性现在已过时。
shape
和 coords
属性一起工作。 coords
属性取决于 shape
属性的值。
rect
circle
poly
default
以下代码显示如何使用图像映射。
<!DOCTYPE HTML>
<html>
<body>
<p>
<img src="http://www.www.juanshu.me/style/download.png" usemap="#mymap"/>
</p>
<map name="mymap">
<area href="a.html" shape="rect" coords="3,5,68,62" alt="test a" />
<area href="b.html" shape="rect" coords="70,5,130,62" alt="test b" />
<area href="c.html" shape="default" alt="test c" />
</map>
</body>
</html>
img
元素上的 usemap
属性将map元素与图像相关联。