AMP

包含图片 & 视频

就像在普通的 HTML 页面上一样,AMP 允许您嵌入 图片视频音频 内容。 了解 AMP 等效项的不同之处,并学习如何在页面中包含它们。

为什么不用 <img>、<video> 和 <audio>?

AMP 不支持用于显示媒体的默认 HTML 对应项,例如 <img>。 我们提供等效的组件,原因如下

虽然它们不受支持,但它们呈现,但 AMP 不会 验证您的页面,并且您将无法获得 AMP 提供的所有好处。

图片

使用 amp-img 元素在您的页面中包含图片,如下所示

<amp-img alt="A beautiful sunset"
  src="/static/inline-examples/images/sunset.jpg"
  width="264"
  height="195">
</amp-img>
在 playground 中打开此代码段

在这个最基本的示例中,图片将显示指定的固定高度和宽度。 至少,需要设置显式的宽度和高度。

在 JavaScript 被禁用时显示图片

由于 <amp-img> 依赖于 JavaScript,如果用户选择禁用脚本,图片将不会显示。 在这种情况下,您应该使用 <img><noscript> 为图片提供一个回退,如下所示

<amp-img src="/static/inline-examples/images/sunset.jpg"
  width="264"
  height="195"
  alt="...">
  <noscript>
    <img src="/static/inline-examples/images/sunset.jpg" width="264" height="195" alt="...">
  </noscript>
</amp-img>
在 playground 中打开此代码段

高级布局

AMP 使创建完全响应式的图片比使用标准的 CSS/HTML 容易得多。 在其最基本的形式中,您所要做的就是添加 layout="responsive"

<amp-img alt="A view of the sea"
  src="/static/inline-examples/images/sea.jpg"
  width="900"
  height="675"
  layout="responsive">
</amp-img>
在 playground 中打开此代码段

继续阅读 – 了解有关高级布局技术的更多信息。

行为和占位符

AMP HTML 运行时可以有效地管理图片资源,根据视口位置、系统资源、连接带宽或其他因素选择延迟或优先加载资源。

继续阅读 – 了解如何为图片提供回退和占位符

动画图片

amp-anim 元素与 amp-img 元素非常相似,并提供了额外的功能来管理动画图片(例如 GIF)的加载和播放。

<amp-anim width="400"
  height="300"
  src="/static/inline-examples/images/wavepool.gif"
  alt="...">
  <amp-img placeholder
    width="400"
    height="300"
    src="/static/inline-examples/images/wavepool.png"
    alt="...">
  </amp-img>
</amp-anim>
在 playground 中打开此代码段

注意 – 在页面的头部包含 <script async custom-element="amp-anim" src="https://cdn.ampproject.org/v0/amp-anim-0.1.js"></script> 以使用此组件。

视频

使用 amp-video 元素在您的页面中包含视频。

仅将此元素用于直接 HTML5 视频文件嵌入。 此元素在 AMP 确定的时间延迟加载 src 属性指定的视频资源。

在视频开始之前包含一个占位符,如果浏览器不支持 HTML5 视频,则包含一个回退,例如

此浏览器不支持 video 元素。

<amp-video controls
  width="640"
  height="360"
  src="/static/inline-examples/videos/kitten-playing.mp4"
  poster="/static/inline-examples/images/kitten-playing.png">
  <div fallback>
    <p>This browser does not support the video element.</p>
  </div>
</amp-video>
在 playground 中打开此代码段

音频

使用 amp-audio 元素在您的页面中包含音频资源。

仅将此元素用于直接 HTML5 音频文件嵌入。 像 AMP 页面中所有嵌入的外部资源一样,此元素在 AMP 确定的时间延迟加载 src 属性指定的音频资源。

如果浏览器不支持 HTML5 音频,则包含一个回退,例如

您的浏览器不支持 HTML5 音频。

<amp-audio width="400"
  height="200"
  src="/static/inline-examples/audio/cat-meow.mp3">
  <div fallback>
    <p>Your browser doesn’t support HTML5 audio.</p>
  </div>
  <source type="audio/mpeg"
    src="/static/inline-examples/audio/cat-meow.mp3">
  <source type="audio/ogg"
    src="/static/inline-examples/audio/cat-meow.ogg">
</amp-audio>
在 playground 中打开此代码段

注意 – 在页面的头部包含 <script async custom-element="amp-audio" src="https://cdn.ampproject.org/v0/amp-audio-0.1.js"></script> 以使用此组件。