返回

Picture

<picture>:HTMLPictureElement

元素包含0或多个元素和一个元素和可选的script-supporting elements(script、template)混合来为不同设备场景提供图像。浏览会先选择最匹配的元素,如果没有匹配的,就选择元素,所选的图像最终都呈现在img元素占据的空间中

<source> 说明
src 资源地址
type 资源类型
srcset 在不同情况下使用的图像
sizes 不同页面布局的图像尺寸
media 应用的媒体查询

示例

media 属性


media 属性允许你提供一个用于给用户代理作为选择 <source> 元素的依据的媒体条件(media condition)(类似于媒体查询)。如果这个媒体条件匹配结果为 false,那么这个 <source> 元素会被跳过。

<picture>
  <source srcset="mdn-logo-wide.png" media="(min-width: 600px)">
  <img src="mdn-logo-narrow.png" alt="MDN">
 </picture>

type 属性


type 属性允许你为 <source> 元素的 srcset 属性指向的资源指定一个 MIME 类型。如果用户代理不支持指定的类型,那么这个 <source> 元素会被跳过
<picture>
  <source srcset="mdn-logo.svg" type="image/svg+xml">
  <img src="mdn-logo.png" alt="MDN">
 </picture>

srcset 属性

srcset="images/team-photo.jpg 1x, images/team-photo-retina.jpg 2x, images/team-photo-full 2048w"

srcset="header640.png 640w, header960.png 960w, header1024.png 1024w, header.png"

srcset="icon32px.png 32w, icon64px.png 64w, icon-retina.png 2x icon-ultra.png 3x icon.svg"

<div class="box">
  <img src="/files/16797/clock-demo-200px.png"
       alt="Clock"
       srcset="/files/16864/clock-demo-200px.png 1x, /files/16797/clock-demo-400px.png 2x">
</div>

js获取img使用的src:img.currentSrc

let box = document.querySelector(".box");let image = box.querySelector("img");
let newElem = document.createElement("p");
newElem.innerHTML = `Image: <code>${image.currentSrc}</code>`;
box.appendChild(newElem);