新增輪播
行動版網頁中另一個常見的功能是輪播。您可以使用 amp-carousel
元件,輕鬆將輪播新增至 AMP 頁面。我們先從簡單的範例開始,例如圖片輪播。
簡易圖片輪播
請務必加入 amp-carousel
元件程式庫,方法是將下列 JavaScript 要求新增至文件 <head>
標記中
<script async custom-element="amp-carousel" src="https://cdn.ampproject.org/v0/amp-carousel-0.1.js"></script>
接著,我們來嵌入簡易圖片輪播,並採用回應式版面配置以及預先定義的寬度和高度。請將下列內容新增至您的網頁
<amp-carousel layout="fixed-height" height="168" type="carousel" >
<amp-img src="mountains-1.jpg" width="300" height="168"></amp-img>
<amp-img src="mountains-2.jpg" width="300" height="168"></amp-img>
<amp-img src="mountains-3.jpg" width="300" height="168"></amp-img>
</amp-carousel>
重新整理您的網頁,您應該就會看到輪播
amp-carousel
元件可以透過多種方式設定。我們來變更 UI,讓畫面一次只顯示一張圖片,並讓輪播的版面配置具備回應性。
如要執行這項操作,請先將 amp-carousel
的 type
從 carousel
變更為 slides
,將 layout
變更為 responsive
,並將 width
設定為 300 (確保同時定義 height
和 width
)。將 "layout=responsive"
屬性新增至 amp-carousel
的 amp-img
子項。
重新載入您的網頁。現在,您看到的畫面會變成一次顯示一個元素,而不是可捲動的元素清單。請嘗試水平滑動以瀏覽各個元素。如果您滑動到第三個元素,就會無法再繼續滑動。
接著,新增 loop
屬性。重新整理網頁,並立即嘗試向左滑動。輪播會無限循環播放。
最後,我們讓這個輪播每 2 秒自動播放一次。將 autoplay
屬性和 delay
屬性 (值為 2000
,例如 delay="2000"
) 新增至 amp-carousel
。
您的最終結果應該會像這樣
<amp-carousel layout="responsive" width="300" height="168" type="slides" autoplay delay="2000" loop>
<amp-img src="mountains-1.jpg" width="300" height="168" layout="responsive"></amp-img>
<amp-img src="mountains-2.jpg" width="300" height="168" layout="responsive"></amp-img>
<amp-img src="mountains-3.jpg" width="300" height="168" layout="responsive"></amp-img>
</amp-carousel>
重新整理網頁並試用看看!
amp-carousel
的類型為 carousel
時,我們使用了 fixed-height
版面配置類型。carousel
類型支援的版面配置類型有限;例如,carousel
類型不支援 responsive
版面配置。顧名思義,fixed-height 元素會佔用可用的空間,但會保持高度不變。對於 fixed-height 元素,您必須定義 height
屬性,而 width
屬性則應設為 auto
或不設定。混合輪播內容
圖片輪播很棒,但如果我們希望輪播中顯示更複雜的內容該怎麼辦?我們來試著混合搭配,將廣告、一些文字和圖片全部放在同一個輪播中。amp-carousel
真的可以一次處理這麼多混合內容嗎?當然可以!
首先,我們將下列樣式新增至您的 <style amp-custom>
,以確保 amp-fit-text
和 amp-carousel
元件可以安全地協同運作
amp-fit-text {
white-space: normal;
}
現在,將您的簡易輪播替換成以下內容
<amp-carousel layout="fixed-height" height="250" type="carousel" >
<amp-img src="blocky-mountains-1.jpg" width="300" height="250"></amp-img>
<amp-ad width="300" height="250"
type="doubleclick"
data-slot="/35096353/amptesting/image/static">
<div placeholder>This ad is still loading.</div>
</amp-ad>
<amp-fit-text width="300" height="250" layout="fixed">
Big, bold article quote goes here.
</amp-fit-text>
</amp-carousel>
重新整理網頁,您應該就會看到像這樣的內容
如要進一步瞭解詳情,請參閱 amp-carousel
元件參考文件。