常用 AMP 元件,速成教學
在打造快閃式網頁時,AMP(Accelerated Mobile Pages)提供了許多專門設計的元件。以下整理最常見且實用的元素,讓你能快速寫出符合最佳化規範的頁面。
amp-img:圖片加速載入
amp-img 是 AMP 內建的圖片元件,支援自動懶載與尺寸預留。只要設定寬高與 layout,就能確保畫面不會因為圖片載入而跳躍。
<amp-img src='https://example.com/photo.jpg' width='400' height='300' layout='responsive'></amp-img>
如果你想在圖片失敗時提供備援,直接加上 fallback 標籤即可:
<amp-img src='https://example.com/photo.jpg' width='400' height='300' layout='fixed'>
<div fallback>圖片無法顯示</div>
</amp-img>
amp-carousel:圖片輪播
輪播是一個常見的 UI 元件,AMP 提供了兩種簡易方式:垂直或水平滑動。設定 autoplay 或 loop 可以讓使用者更順暢地瀏覽內容。
<amp-carousel width='400' height='300' layout='fixed' type='slides' autoplay='true'>
<amp-img src='https://example.com/img1.jpg' width='400' height='300'></amp-img>
<amp-img src='https://example.com/img2.jpg' width='400' height='300'></amp-img>
</amp-carousel>
amp-form:表單提交
AMP 的表單需要使用 amp-form 並指定 action-xhr。這樣就能在不重新載入頁面的情況下送出資料,並直接顯示回覆訊息。
<form method='post' action-xhr='/submit' target='_top'>
<label>姓名:<input type='text' name='name'></label>
<button submit>送出</button>
<div submit-success>感謝您的留言!</div>
<div submit-error>發生錯誤,請再試一次。</div>
</form>
amp-accordion:可折疊內容區塊
如果頁面需要多段資訊而又不想佔用過多空間,amp-accordion 能讓使用者點擊展開或收合。
<amp-accordion>
<section expanded>第一節內容
<p>詳細說明文字。</p>
</section>
<section>第二節內容
<p>更多資訊。</p>
</section>
</amp-accordion>
amp-video:影片播放控制
AMP 內建的 amp-video 支援多種格式與自動播放設定。只要把 mp4 或 webm 放進來即可。
<amp-video width='640' height='360' layout='responsive' controls>
<source src='https://example.com/video.mp4' type='video/mp4'>
</amp-video>
amp-social-share:社群分享按鈕
為了讓內容能被更廣泛傳播,amp-social-share 提供簡易的分享介面。可自訂平台與樣式。
<amp-social-share type='facebook'></amp-social-share>
<amp-social-share type='twitter'></amp-social-share>
amp-ad:廣告插入
如果你想在頁面中加入廣告,只要使用 amp-ad 並提供 ad-slot、data-ad-client 等參數即可。AMP 會自動處理非同步載入,確保不影響主內容。
<amp-ad width='300' height='250'
type='doubleclick'
data-ad-client='ca-pub-xxxx'
data-ad-slot='yyyy'>
</amp-ad>
amp-bind:動態互動
amp-bind 允許你在 AMP 頁面內使用屬性綁定,實現簡單的互動效果,例如點擊切換文字或顏色。
<button on='tap:myDiv.toggleClass(myClass)'>點我</button>
<div id='myDiv' class='initial'>內容區塊</div>
amp-list:遠端資料載入
當你需要從 API 取得 JSON 並渲染成列表,amp-list 是最佳選擇。設定 src 與 template,就能自動將資料轉換為 HTML。
<amp-list width='auto' height='100' layout='fixed-height' src='/api/items'>
<template type='amp-mustache'>
<div>{{title}}</div>
</template>
</amp-list>
amp-selector:可選擇項目
如果你想在頁面上提供多種選項並觸發事件,amp-selector 可以輕鬆實現。設定 option、value 與 on 事件即可。
<amp-selector on='select:AMP.setState({selectedColor: this.value})'>
<option value='red' selected>紅色</option>
<option value='blue'>藍色</option>
</amp-selector>
以上就是最常用的 AMP 元件與速成範例。只要在 head 區塊加上對應的腳本(例如 <script async custom-element='amp-img' src='https://cdn.ampproject.org/v0/amp-img-0.1.js'></script>),就能直接使用這些元件。祝你開發順利!