iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 25
1
Modern Web

AMP系列 第 25

AMP(Lession 25) - 用 position observer 實現 scrolling 頁面時的一些互動效果

用 position observer 實現 scrolling 頁面時的一些互動效果

在 amp 的世界裡,我們可以可以利用 scrolling 時做些事唷!!

先來看張圖好了↓↓↓

只要運用了 amp-position-observer (垂直捲動),就算一行的 js 都不寫,也可以玩出些小東西。如上圖,我們可以看到,隨著垂直的 scrolling ,可以旋轉時針。

今天先來介紹一下 amp-position-observer

Required Script

<script async custom-element="amp-position-observer" src="https://cdn.ampproject.org/v0/amp-position-observer-0.1.js"></script>

範例解說

我們利用上面那個效果的原始檔來解說

<amp-animation id="clockAnim" layout="nodisplay">
  <script type="application/json">
    {
    "duration": "3s", // 3秒
    "fill": "both",
    "direction": "alternate",
    "animations": [
      {
        "selector": "#clock-scene .clock-hand", // 選取物件
        "keyframes": [ // 動畫,設定了我們要讓物件如何動作
          { "transform": "rotate(-180deg)" },
          { "transform": "rotate(0deg)" }
        ]
      }
    ]
  }
  </script>
</amp-animation>

<!-- The clock container -->
<div id="clock-scene">
  <!-- 用 seekTo 來監聽 scroll 事件 -->
  <amp-position-observer
    intersection-ratios="1"
    on="scroll:clockAnim.seekTo(percent=event.percent)"
    layout="nodisplay">
  </amp-position-observer>
  <amp-img layout="responsive" width=2 height=1.5 src="./img/clock.jpg">
    <div class="clock-hand"></div><!-- 這就是上面選取的物件,會做180度的旋轉 -->
  </amp-img>
</div>

Attributes

target - 目標,非必填

指定要觀察的元素的ID。 如果未指定,則將 <amp-position-observer> 的父級用作目標。

intersection-ratios - 交叉比率,非必填

定義在 <amp-position-observer> 觸發其任何事件之前。 該值是介於 01 之間的數字(默認值為 0

  • intersection-ratios="0" - 只要 target 的一個像素進入 viewport ,就會觸發 enter ,並且只要 target 的最後一個像素離開 viewport ,就會觸發 exit

  • intersection-ratios="0.5" - 只要 target 的 50% 進入 viewport ,就會觸發 enter ;只要 target 不到 50% ,就會觸發 exit

  • intersection-ratios="1" - 表示當 target 完全可見時觸發 enter ;一旦單個像素離開 viewport,就會觸發 exit

  • intersection-ratios="0 1" - target 進入/退出時是從頂部(使用0)還是從底部(使用1)

viewport-margins - viewport margin,非必填

pxvh 值,沒有單位的數字將被假定為 px。 默認為0。

您可以通過提供兩個值(top 、 bottom)為頂部與底部指定不同的值;例如: viewport-margins="100px 10vh"

once - enterexitscroll event 只觸發一次,非必填


現在,我們知道基本的用法了,我們就可以做出如範例更複雜的互動。


參考來源:


上一篇
AMP(Lession 24) - AMP 中的 iframe
下一篇
AMP(Lession 26) - Google VR 圖片
系列文
AMP30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言