详解HTML5中的picture元素响应式处理图片

2020-04-25 08:11:07易采站长站整理

<source media="(min-width: 320px) and (max-width: 640px) and (orientation: landscape)" srcset="img/minpic_landscape.png">
<source media="(min-width: 320px) and (max-width: 640px) and (orientation: portrait)" srcset="img/minpic_portrait.png">
<source media="(min-width: 640px) and (orientation: landscape)" srcset="img/middlepic_landscape.png">
<source media="(min-width: 640px) and (orientation: portrait)" srcset="img/middlepic_portrait.png">
<img src="img/picture.png" alt="this is a picture">
</picture>

3.如下栗子中添加了屏幕像素密度作为条件;当像素密度为2x时加载_retina.png 2x 的图片,当像素密度为1x时加载无retina后缀的图片;


<picture>
<source media="(min-width: 320px) and (max-width: 640px)" srcset="img/minpic.png,img/minpic_retina.png 2x">
<source media="(min-width: 640px)" srcset="img/middle.png,img/middle_retina.png 2x">
<img src="img/picture.png,img/picture_retina.png 2x" alt="this is a picture">
</picture>

4.如下栗子中添加图片文件格式作为条件,当支持webp格式图片时加载webp格式图片,当不支持时加载png格式图片;


<picture>
<source type="image/webp" srcset="img/picture.webp">
<img src="img/picture.png" alt="this is a picture">
</picture>

5.如下例子中添加宽度描述;页面会根据当前尺寸选择加载不大于当前宽度的最大的图片;


<img src="picture-160.png" alt="this is a picture"
sizes="90vw"
srcset="picture-160.png 160w,
picture-320.png 320w,
picture-640.png 640w,
picture-1280.png 1280w">

6.如下例子中添加sizes属性;当窗口宽度大于等于800px时加载对应版本的图片;


<source media="(min-width: 800px)"
sizes="90vw"
srcset="picture-landscape-640.png 640w,
picture-landscape-1280.png 1280w,
picture-landscape-2560.png 2560w">
<img src="picture-160.png" alt="this is a picture"
sizes="90vw"
srcset="picture-160.png 160w,
picture-320.png 320w,
picture-640.png 640w,
picture-1280.png 1280w">

兼容性:

目前只有Chrome , Firefox , Opera 对其兼容性较好,具体兼容性如图:

优点: