AMP
  • 網站

amp-img

簡介

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

設定

amp-img 是一個內建元素,會透過 AMP 執行階段自動匯入。

<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>

基本用法

簡單的 回應式 圖片 - widthheight 用於判斷長寬比。使用 alt 指定可做為圖片替代文字的文字。

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

HTML 5.1 針對 建立可做為圖片替代文字的文字 提供指引。

srcset

使用 srcset 指定適用於不同檢視區寬度和像素密度的不同圖片 (變更瀏覽器視窗的寬度即可進行測試)。

<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>

離線回退

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>

無指令碼

如果您想要確保停用 JavaScript 的使用者也能看到您的圖片,您可以將額外的 img 元素新增至 noscript 標記內。這也能讓沒有 JavaScript 執行階段的網路爬蟲程式探索您的圖片。

<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-imgsrc 網址。如果圖片的內容/意義有所變更,請記得同時變更 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

以下是使用彈性版面配置垂直置中 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 上編輯範例