滚动到顶部
简介
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