捲動至頂端
簡介
amp-position-observer 結合 amp-animation 可以用來實作捲動至頂端按鈕。此模式常用於電子商務頁面,使用者必須捲動瀏覽長長的商品列表。
設定
匯入 amp-position-observer 擴充功能
<script async custom-element="amp-position-observer" src="https://cdn.ampproject.org/v0/amp-position-observer-0.1.js"></script>
匯入 amp-animation 擴充功能
<script async custom-element="amp-animation" src="https://cdn.ampproject.org/v0/amp-animation-0.1.js"></script>
樣式
這些範例使用的 CSS 包含在此處以供參考。
這些規則僅用於使範例運作,並非此處涵蓋概念的基礎。
<style amp-custom>
:root {
--color-primary: #005AF0;
--color-secondary: #00DCC0;
--color-text-light: #fff;
--space-2: 1rem; /* 16px */
--box-shadow-1: 0 1px 1px 0 rgba(0,0,0,.14), 0 1px 1px -1px rgba(0,0,0,.14), 0 1px 5px 0 rgba(0,0,0,.12);
}
.scrollToTop {
color: var(--color-text-light);
font-size: 1.4em;
box-shadow: var(--box-shadow-1);
width: 50px;
height: 50px;
border-radius: 50%;
border: none;
outline: none;
background: var(--color-primary);
z-index: 9999;
bottom: var(--space-2);
right: var(--space-2);
position: fixed;
opacity: 0;
visibility: hidden;
}
.spacer {
width: 100vw;
max-width: 700px;
height: 200vh;
background-color: var(--color-secondary);
}
/* we move the anchor down to componsate the fixed header */
.target {
position: relative;
}
.target-anchor {
position: absolute;
top: -72px;
left: 0;
}
</style>
位置觀察器與動畫
我們新增了一個 id 為 top-page
的元素,以便稍後在捲動時參考。當使用者開始捲動且頂端元素不再可見時,我們使用 amp-position-observer
來啟動動畫。
<h3 class="target">
<a class="target-anchor" id="top"></a>
This is the target.
<amp-position-observer on="enter:hideAnim.start; exit:showAnim.start" layout="nodisplay">
</amp-position-observer>
</h3>
我們使用 2 個 amp-animation
元素來觸發按鈕的顯示。第一個用於使按鈕可見...
<amp-animation id="showAnim" layout="nodisplay">
<script type="application/json">
{
"duration": "200ms",
"fill": "both",
"iterations": "1",
"direction": "alternate",
"animations": [
{
"selector": "#scrollToTopButton",
"keyframes": [
{ "opacity": "1", "visibility": "visible" }
]
}
]
}
</script>
</amp-animation>
... 第二個用於新增按鈕。
<amp-animation id="hideAnim" layout="nodisplay">
<script type="application/json">
{
"duration": "200ms",
"fill": "both",
"iterations": "1",
"direction": "alternate",
"animations": [
{
"selector": "#scrollToTopButton",
"keyframes": [
{ "opacity": "0", "visibility": "hidden" }
]
}
]
}
</script>
</amp-animation>
這是一個虛擬間隔器。
<div class="spacer"></div>
捲動至頂端按鈕
我們使用 scrollTo
動作在點擊按鈕時捲動頁面。如需更多關於動作的資訊,請參閱此處。
<button id="scrollToTopButton" on="tap:top.scrollTo(duration=200)" class="scrollToTop">⌃</button>
需要更多說明嗎?
若此頁面上的說明未能涵蓋您的所有問題,請隨時與其他 AMP 使用者交流,討論您的確切使用案例。
前往 Stack Overflow 功能未說明?AMP 專案強烈鼓勵您的參與和貢獻!我們希望您能成為我們開放原始碼社群的長期參與者,但我們也歡迎您針對您特別感興趣的問題做出一次性貢獻。
在 GitHub 上編輯範例-
由 @kul3r4 撰寫