您现在的位置是:网站首页 > 图像标签(img)的基本使用文章详情
图像标签(img)的基本使用
陈川
【
HTML
】
10284人已围观
3156字
图像标签(img)的基本使用
<img>
标签是HTML中用于嵌入图像的核心元素。它不需要闭合标签,通过src属性指定图像源文件路径,alt属性提供替代文本。图像标签支持多种属性控制显示效果和响应式行为。
基本语法结构
最基本的图像标签写法只需要src和alt两个属性:
<img src="logo.png" alt="公司标志">
src属性支持以下路径形式:
- 相对路径:
"images/pic.jpg"
- 绝对路径:
"/static/photo.png"
- 完整URL:
"https://example.com/banner.jpg"
alt属性在图像无法显示时呈现,也是屏幕阅读器读取的内容。即使留空也应保留该属性:
<img src="decorative.jpg" alt="">
尺寸控制属性
width和height属性可以指定显示尺寸(单位默认为像素):
<img src="product.jpg" alt="商品展示" width="300" height="200">
现代开发实践中建议只设置其中一个属性保持比例:
<img src="portrait.png" alt="人物肖像" width="500">
CSS控制尺寸更为推荐:
<img src="landscape.jpg" alt="风景照" style="max-width: 100%;">
响应式图像处理
通过srcset和sizes属性实现响应式图像:
<img src="small.jpg"
srcset="small.jpg 480w, medium.jpg 768w, large.jpg 1200w"
sizes="(max-width: 600px) 480px, 800px"
alt="响应式图像示例">
picture元素配合source标签提供更精细控制:
<picture>
<source media="(min-width: 1200px)" srcset="large.jpg">
<source media="(min-width: 768px)" srcset="medium.jpg">
<img src="small.jpg" alt="自适应图像">
</picture>
图像映射与交互
结合map和area标签创建可点击区域:
<img src="worldmap.png" alt="世界地图" usemap="#map1">
<map name="map1">
<area shape="rect" coords="50,50,150,150" href="europe.html" alt="欧洲">
<area shape="circle" coords="200,200,50" href="asia.html" alt="亚洲">
</map>
性能优化技巧
使用loading属性实现懒加载:
<img src="lazy.jpg" alt="延迟加载" loading="lazy">
现代浏览器支持的decoding属性:
<img src="highres.jpg" alt="高清图" decoding="async">
可访问性增强
为复杂图像添加详细描述:
<img src="chart.png" alt="2023年销售趋势图" longdesc="chart-desc.html">
使用figure和figcaption提供图文关联:
<figure>
<img src="experiment.jpg" alt="实验过程">
<figcaption>图1:化学反应过程示意图</figcaption>
</figure>
跨域与安全控制
使用crossorigin属性处理跨域图像:
<img src="https://cdn.example.com/image.jpg" alt="CDN图片" crossorigin="anonymous">
防止热链的referrerpolicy设置:
<img src="protected.jpg" alt="保护图片" referrerpolicy="no-referrer">
动态图像处理示例
JavaScript动态修改图像示例:
<img id="dynamicImg" src="default.jpg" alt="动态图像">
<script>
document.getElementById('dynamicImg').src = 'new-image.jpg';
</script>
响应鼠标事件的图像切换:
<img src="normal.png" alt="交互图像"
onmouseover="this.src='hover.png'"
onmouseout="this.src='normal.png'">
现代图像格式支持
WebP格式的渐进增强方案:
<picture>
<source type="image/webp" srcset="image.webp">
<img src="image.jpg" alt="现代格式图像">
</picture>
AVIF格式检测与回退:
<picture>
<source type="image/avif" srcset="photo.avif">
<source type="image/webp" srcset="photo.webp">
<img src="photo.jpg" alt="高质量图像">
</picture>
图像与CSS集成
通过object-fit控制图像填充方式:
<img src="portrait.jpg" alt="自适应填充" style="width: 200px; height: 300px; object-fit: cover;">
使用CSS滤镜效果:
<img src="original.jpg" alt="滤镜效果" style="filter: grayscale(50%) blur(1px);">
打印样式优化
为打印媒体指定高分辨率图像:
<img src="lowres.jpg" alt="打印优化"
srcset="highres.jpg 2x"
media="print">
使用CSS确保打印时图像完整显示:
<style>
@media print {
img { max-width: 100% !important; }
}
</style>
上一篇: 图像映射的使用
下一篇: 图像的替代文本(alt属性)