📜  如何在 Google AMP 中使用 amp-bind 动态更改更新图像大小?(1)

📅  最后修改于: 2023-12-03 15:38:16.166000             🧑  作者: Mango

在 Google AMP 中使用 amp-bind 动态更改更新图像大小

对于那些在谷歌 AMP 中自定义交互元素的开发人员来说,跟 amp-bind 一起使用来动态更新图像大小是一个有用的技术。当加载页面时,可以将图像的大小设置为默认值,而当用户与页面进行交互时,图像大小可以根据用户行为进行自适应。

以下是如何在 Google AMP 中使用 amp-bind 动态更改图像大小的步骤。

1.在 中引入 amp-bind 组件

首先,在页面的头部引入 amp-bind 组件,以便在页面中使用。

<head>
  <script async src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>
</head>
  1. 设置图像大小为默认值

将图像大小设置为默认值。在以下示例中,我们将图像大小设置为 300x300 像素。

<amp-img src="your-image.jpg"
  width="300"
  height="300">
</amp-img>
  1. 给一个动态元素添加 ID

为了让 amp-bind 可以动态更新元素,您需要向要更改的元素添加一个 ID。在以下示例中,我们将 ID 设置为“my-img”。

<amp-img id="my-img" src="your-image.jpg"
  width="300"
  height="300">
</amp-img>
  1. 添加一个交互元素

您需要添加一个“按钮”(在此示例中,我们将其设置为

<button on="tap:AMP.setState({newWidth: 400, newHeight: 400})">Enlarge Image</button>

在此代码中,当用户点击按钮时,amp-bind 将触发状态更新(由 AMP.setState() 设置),并将图像的新大小设置为 400x400 像素。

  1. 使用 amp-bind 更新图像大小

最后,在图像元素中使用 amp-bind,以便在状态有所更改时自适应图像大小。

<amp-img id="my-img" src="your-image.jpg"
  [width]="newWidth"
  [height]="newHeight">
</amp-img>

注意:在此示例中,我们将 amp-bind 与 元素一起使用,该元素支持属性绑定。因此,我们将新的图像宽度和高度设置为 [width] 和 [height] 属性。

完整代码示例:

<!doctype html>
<html ⚡>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
    <script async src="https://cdn.ampproject.org/v0.js"></script>
    <script async src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>
    <style amp-custom>
      button {
        background-color: blue;
        color: white;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <h1>Dynamic Image Resizing with AMP Bind</h1>

    <amp-img id="my-img" src="your-image.jpg"
      width="300"
      height="300">
    </amp-img>

    <button on="tap:AMP.setState({newWidth: 400, newHeight: 400})">Enlarge Image</button>

    <amp-img id="my-img" src="your-image.jpg"
      [width]="newWidth"
      [height]="newHeight">
    </amp-img>
  </body>
</html>

该代码将在页面上显示一个图像,当用户点击“Enlarge Image”按钮时,图像的大小将自动更改为更大的尺寸(使用 amp-bind 和状态更新)。

参考资料: