AMP
  • 網站

amp-img

簡介

AMP HTML 檔案不支援一般的 HTML `img` 標籤。AMP 透過 `amp-img` 提供強大的替代方案。

設定

`amp-img` 是一個內建元素,並透過 AMP runtime 自動匯入。

<script async src="https://cdn.ampproject.org/v0.js"></script>

您可以使用 `amp-bind` 擴充功能來動態變更圖片。

<script async custom-element="amp-bind" src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>

基本用法

一個簡單的響應式圖片 - `width` 和 `height` 用於決定長寬比。使用 `alt` 指定可作為圖片替代文字的內容。

<amp-img src="/static/samples/img/amp.jpg" width="1080" height="610" layout="responsive" alt="AMP"></amp-img>

srcset

使用 `srcset` 為不同的 viewport 寬度和像素密度指定不同的圖片 (變更瀏覽器視窗的寬度來測試)。

<amp-img src="/static/samples/img/amp.jpg" srcset="/static/samples/img/amp.jpg 1080w, /static/samples/img/amp-900.jpg 900w, /static/samples/img/amp-800.jpg 800w,
/static/samples/img/amp-700.jpg 700w, /static/samples/img/amp-600.jpg 600w, /static/samples/img/amp-500.jpg 500w, /static/samples/img/amp-400.jpg 400w,
/static/samples/img/amp-300.jpg 300w, /static/samples/img/amp-200.jpg 200w, /static/samples/img/amp-100.jpg 100w" width="1080" height="610" layout="responsive" alt="AMP"></amp-img>

離線 fallback

`amp-img` 支援 AMP 的 通用屬性,這表示您可以顯示 `fallback`,以防圖片無法載入。這非常適合為您的 AMP 新增離線支援。

離線
<amp-img src="/static/samples/img/does-not-exist.jpg" width="300" height="100" layout="responsive" alt="a non-existent image">
  <div fallback>offline</div>
</amp-img>

No script

如果您想確保停用 JavaScript 的使用者可以看到您的圖片,您可以將額外的 `img` 元素新增到 `noscript` 標籤內。這也讓沒有 JavaScript runtime 的網路爬蟲可以發現您的圖片。

<amp-img src="/static/samples/img/amp.jpg" width="475" height="268" layout="responsive" alt="AMP">
  <noscript>
    <img src="/static/samples/img/amp.jpg" width="475" height="268" alt="AMP">
  </noscript>
</amp-img>

隱藏載入指示器

使用 `noloading` 屬性來隱藏頁面載入時的載入指示器。建議用於標誌和小型圖片/圖示。

<amp-img src="/static/samples/img/amp_by_example_logo.svg" width="208" height="40" alt="AMP by Example" noloading></amp-img>

動態變更 src

您可以使用 `amp-bind` 來動態變更 `amp-img` 的 `src` URL。如果圖片的內容/意義變更,請記得也變更 `alt`。

<amp-img src="https://unsplash.it/300/200/?image=100" width="300" height="200" alt="Example image" [src]="myImageUrl" [alt]="myImageAlt">
</amp-img>
<button on="tap:AMP.setState({ myImageUrl: 'https://unsplash.it/300/200/?image=200', myImageAlt: 'Another example image' })">Change image</button>

垂直置中 amp-img

這是一個使用 flex layout (src) 垂直置中 `amp-img` 的簡單方法

<div class="outer">
   <amp-img class="inner" layout="responsive" src="https://unsplash.it/300/200" width="3" height="2" alt="a vertically centered amp-img">
   </amp-img>
 </div>

...以及這裡的 CSS

.inner{
  flex-basis: 0;
  -ms-flex-preferred-size: 0;
  -webkit-box-flex: 1;
  -ms-flex-positive: 1;
  flex-grow: 1;
}
.outer {
  height: 320px; /* adjust to your needs */
  display: flex;
  flex-wrap: wrap;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}
需要更多說明嗎?

如果此頁面上的說明沒有涵蓋您的所有問題,請隨時聯繫其他 AMP 使用者,討論您的確切使用案例。

前往 Stack Overflow
未說明的特色功能?

AMP 專案強烈鼓勵您的參與和貢獻!我們希望您能成為我們開源社群的持續參與者,但我們也歡迎您針對您特別感興趣的問題做出一次性貢獻。

在 GitHub 上編輯範例