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 中開啟此程式碼片段

注意 – 在您頁面的 head 中加入 <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 中開啟此程式碼片段

注意 – 在您頁面的 head 中加入 <script async custom-element="amp-audio" src="https://cdn.ampproject.org/v0/amp-audio-0.1.js"></script>,即可使用此元件。