AMP

AMP 交互性介绍

重要提示:此文档不适用于您当前选择的格式广告

这些指南概述了如何创建交互式 AMP 页面。交互性对于现代 Web 至关重要。构建独特而令人愉悦的体验可以吸引用户,使他们留在您的网站上。AMP 提供了满足常见交互性需求的开箱即用解决方案,同时也提供了高度可定制和灵活的解决方案。

构建交互式体验可能感觉不太传统,而且确实不是!但这并不意味着它更困难。一旦您了解了概念并理解了语法,使用 AMP 构建许多交互式体验非常容易。

AMP 中有几个级别的交互性。您可以将一个、多个、全部或不应用到 AMP 页面。阅读本指南的各个部分,了解如何在 AMP 中构建交互性。

交互性基础

本指南概述了 AMP 提供的内置交互性。它解释了如何轻松实现常见的原语,例如隐藏和显示元素。

你好,世界!

  <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 提供了针对常见 Web 小部件和交互性的解决方案,但每个网站都有自己的需求。AMP 通过三个组件拥抱高度个性化的体验:amp-selectoramp-bindamp-script。这三个组件没有默认 UI。相反,它们用于创建基于选择的界面并构建响应用户交互的动态页面。

<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 组件和概念,这些组件和概念支持在客户端进行渲染。