AMP

AMP 的互動性簡介

這些指南概述了如何建立互動式 AMP 頁面。互動性對於現代網路至關重要。建立獨特且令人愉悅的體驗可以吸引使用者,讓他們留在您的網站上。AMP 針對常見的互動性需求提供了開箱即用的解決方案,同時也提供了高度可自訂和彈性的解決方案。

建構互動式體驗可能感覺不傳統,而且確實如此! 但這並不意味著它更困難。一旦您了解概念並理解語法,許多互動式體驗都可以使用 AMP 輕鬆建構。

AMP 中有幾個互動性層次。您可以將一個、多個、全部或全部都不應用於 AMP 頁面。閱讀本指南的章節,了解如何在 AMP 中建構互動性。

互動性基礎

本指南概述了 AMP 提供的內建互動性。它說明了如何輕鬆實作常見的基本功能,例如隱藏和顯示元素。

Hello World!

  <h1 id="hello">Hello World!</h1>
  <button on="tap:hello.hide">Hide</button>
  <button on="tap:hello.show">Show</button>
  <button on="tap:hello.toggleVisibility">Toggle</button>
在 Playground 中開啟此程式碼片段

從這裡開始學習基礎知識,您可以建構這些基礎知識並將其與其他互動可能性結合。

使用 AMP 元件的現成互動性

AMP 最強大的優勢之一是其廣泛的現成元件函式庫。它們中的許多都是互動式元素,您可以自訂和組合這些元素來建立獨特的體驗!

  <amp-sidebar id="sidebar" class="sample-sidebar" layout="nodisplay" side="right">
    <h3>Sidebar</h3>
    <amp-accordion id="my-accordion" disable-session-states>
      <section>
        <h2>Section 1</h2>
        <p>Content in section 1.</p>
      </section>
      <section>
        <h2>Section 2</h2>
        <div>Content in section 2.</div>
      </section>
      <section expanded>
        <h2>Section 3</h2>
        <amp-img src="/static/inline-examples/images/squirrel.jpg" width="320" height="256" alt="Photo of a squirrel"></amp-img>
      </section>
    </amp-accordion>
    <button on="tap:sidebar.close">Close sidebar</button>
    <button on="tap:sidebar.toggle">Toggle sidebar</button>
  </amp-sidebar>
  <button on="tap:sidebar.toggle">Toggle sidebar</button>
  <button on="tap:sidebar.open">Open sidebar</button>
在 Playground 中開啟此程式碼片段

本指南介紹了最常見的互動式元件,並概述了實作模式。

建構個人化的互動體驗

雖然 AMP 為常見的網路小工具和互動性提供了解決方案,但每個網站都有自己的需求。AMP 透過三個元件擁抱高度個人化的體驗:amp-selectoramp-bindamp-script。這三個元件沒有預設的使用者介面。相反地,它們用於建立基於選擇的介面,並建構響應使用者互動的動態頁面。

<head>
  <meta
    name="amp-script-src"
    content="sha384-qdYQLoj2SRKXBu33BwIoyRKorw0b0nQ8UPIoIMc9wL8KVLcKODSAK52yNGQNS_vN"
  />
  <style amp-custom>
    .clickedButton {
      border: 5px solid green;
    }
  </style>
</head>
<body>
<amp-script width="200" height="100" script="hello-world" [class]="scriptStyle">
  <button>Hello amp-script!</button>
</amp-script>
<script id="hello-world" type="text/plain" target="amp-script">
  const btn = document.querySelector('button');
  btn.addEventListener('click', () => {
    document.body.textContent = 'Hello World!';
    AMP.setState({ scriptStyle: "clickedButton" })
  });
</script>
</body>
在 Playground 中開啟此程式碼片段

使用本指南作為了解這三者之間差異的入門,了解是否以及如何將它們彼此組合並與頁面元素一起使用。

客戶端渲染

本指南概述了 AMP 中的客戶端渲染可能性。預設情況下,AMP 頁面是伺服器端渲染的。但是,在某些情況下,有必要在客戶端動態渲染資料,例如文章列表或使用者購物車中的商品。

查看客戶端篩選範例。

閱讀客戶端渲染以開始使用 AMP 元件和概念,這些元件和概念可以實現客戶端渲染。