• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Universal Methods
2
3>  **NOTE**
4>
5>  This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
6
7After a component is assigned the **id** attribute, you can use the ID to obtain the component objects and call functions.
8
9## animate
10
11animate( keyframes: Keyframes, options: Options): void
12
13- Parameters
14
15  | Name      | Type      | Mandatory | Description                                                  |
16| --------- | --------- | --------- | ------------------------------------------------------------ |
17  | keyframes | keyframes | Yes       | Sets the animation style.                                    |
18  | options   | Options   | Yes       | Array of objects used to set animation attributes. For details, see Options. |
19
20  **Table 1** keyframes
21
22  | Attribute | Type          | Description                                                  |
23| --------- | ------------- | ------------------------------------------------------------ |
24  | frames    | Array\<Style> | Array of objects used to set animation attributes. For details about style attributes, see Style attributes. |
25
26  **Table 2** Style attributes
27
28  | Name               | Type                                           | Default Value   | Description                                                  |
29| ------------------ | ---------------------------------------------- | --------------- | ------------------------------------------------------------ |
30  | width              | number                                         | -               | Width set for the component during playback of the animation. |
31| height             | number                                         | -               | Height set for the component during playback of the animation. |
32  | backgroundColor    | \<color>                                        | none            | Background color set for the component during playback of the animation. |
33| opacity            | number                                         | 1               | Opacity set for the component. The value ranges from **0** to **1**. |
34  | backgroundPosition | string                                         | -               | The value format is **x y**, in percentage or pixels.<br>The first value indicates the horizontal position, and the second value indicates the vertical position.<br>If only one value is specified, the other value is **50%** by default. |
35  | transformOrigin    | string                                         | 'center center' | Origin position of the transformed element.<br>The first value indicates the x-axis position. The value can be **left**, **center**, **right**, a length, or a percentage.<br>The second value indicates the y-axis position. The value can be **top**, **center**, **bottom**, a length, or a percentage. |
36  | transform          | [Transform](js-components-common-animation.md) | -               | Transformation type set for a transformed element.           |
37  | offset             | number                                         | -               | The value of **offset** must be within (0.0,1.0] and sorted in ascending order if it is provided.<br>If there are only two frames, **offset** can be left empty.<br>If there are more than two frames, **offset** is mandatory. |
38
39  **Table 3** Options description
40
41  | Name        | Type             | Default Value | Description                                                  |
42  | ----------- | ---------------- | ------------- | ------------------------------------------------------------ |
43  | duration    | number           | 0             | Duration for playing the animation, in milliseconds.         |
44| easing      | string           | linear        | Time curve of the animation. For details about the supported types, see **Available values of the easing attribute**. |
45  | delay       | number           | 0             | Delay for the animation start. The default value indicates no delay. |
46| iterations  | number \| string | 1             | Number of times the animation will be played. **number** indicates a fixed number of playback operations, and **Infinity** indicates an unlimited number of playback operations. |
47  | direction<sup>6+</sup> | string           | normal        | Mode of playing the animation.   <br>- **normal**: Plays the animation in forward loop mode.  <br>- **reverse**: Plays the animation in reverse loop mode.  <br>- **alternate**: Plays the animation in alternating loop mode. When the animation is played for an odd number of times, the playback is in forward direction. When the animation is played for an even number of times, the playback is in backward direction.  <br>- **alternate-reverse**: Plays the animation in reverse-alternating loop mode. When the animation is played for an odd number of times, the playback is in backward direction. When the animation is played for an even number of times, the playback is in forward direction. |
48| fill        | string           | none          | Start and end styles of the animation.   <br>- **none**: No style is applied to the target before or after the animation is executed.  <br>- **forwards**: The target keeps the state at the end of the animation (defined in the last key frame) after the animation is executed.  <br>- **backwards**<sup>6+</sup>: The animation uses the value defined in the first key frame during the **animation-delay**. When **animation-direction** is set to **normal** or **alternate**, the value in the **from** key frame is used. When **animation-direction** is set to **reverse** or **alternate-reverse**, the value in the **to** key frame is used.  <br>- **both**<sup>6+</sup>: The animation follows the **forwards** and **backwards** rules. |
49
50  **Table 4** Available values of the easing attribute
51
52  | Type                                      | Description                                                  |
53  | ----------------------------------------- | ------------------------------------------------------------ |
54  | linear                                    | The animation speed keeps unchanged.                         |
55  | ease-in                                   | The animation starts at a low speed. **cubic-bezier(0.42, 0.0, 1.0, 1.0)**. |
56  | ease-out                                  | The animation ends at a low speed. **cubic-bezier(0.0, 0.0, 0.58, 1.0)**. |
57| ease-in-out                               | The animation starts and ends at a low speed. **cubic-bezier(0.42, 0.0, 0.58, 1.0)**. |
58  | friction                                  | Damping curve, **cubic-bezier(0.2, 0.0, 0.2, 1.0)**.         |
59| extreme-deceleration                      | Extreme deceleration curve, **cubic-bezier(0.0, 0.0, 0.0, 1.0)**. |
60  | sharp                                     | Sharp curve, **cubic-bezier(0.33, 0.0, 0.67, 1.0)**.         |
61| rhythm                                    | Rhythm curve, **cubic-bezier(0.7, 0.0, 0.2, 1.0)**.          |
62  | smooth                                    | Smooth curve, **cubic-bezier(0.4, 0.0, 0.4, 1.0)**.          |
63  | cubic-bezier(x1, y1, x2, y2)              | You can customize an animation speed curve in the **cubic-bezier()** function. The x and y values of each input parameter must be between 0 and 1. |
64  | steps(number, step-position)<sup>6+</sup> | Step curve.<br>The **number** must be set and only an integer is supported.<br>**step-position** is optional. It can be set to **start** or **end**. The default value is **end**. |
65
66- Return value
67
68  The **animation** attributes are as follows.
69
70  | Attribute | Type    | Description                                                  |
71| --------- | ------- | ------------------------------------------------------------ |
72  | finished  | boolean | Read-only attribute, which indicates whether the animation playback is complete. |
73  | pending   | boolean | Read-only attribute, which indicates whether the animation is waiting for the completion of other asynchronous operations (for example, start an animation with a delay). |
74  | playState | string  | Read-write attribute, which indicates the playback status of the animation:   <br>- **idle**: The animation is not running (playback ended or not started).  <br>- **running**: The animation is running.  <br>- **paused**: The animation is paused.  <br>- **finished**: Animation playback ends. |
75  | startTime | number  | Read-write attribute, which indicates the animation start time. This attribute is similar to **delay** in the **options** attribute. |
76
77  Methods for animation
78
79  | Method  | Parameter | Description                     |
80| ------- | --------- | ------------------------------- |
81  | play    | -         | Plays the animation.            |
82| finish  | -         | Ends the animation.             |
83  | pause   | -         | Pauses the animation.           |
84  | cancel  | -         | Cancels the animation.          |
85  | reverse | -         | Plays the animation in reverse. |
86
87  Events for animation
88
89  | Event   | Description                         |
90| ------- | ----------------------------------- |
91  | start<sup>6+</sup> | The animation starts.               |
92| cancel  | The animation is forcibly canceled. |
93  | finish  | The animation playback is complete. |
94| repeat  | The animation repeats.              |
95
96- Example
97
98```html
99<!-- xxx.hml -->
100<div class="container">
101  <div id="idName" class="box"></div>
102  <div class="buttonBox">
103    <button @click="start">
104      start
105    </button>
106    <button @click="cancel">
107      cancel
108    </button>
109  </div>
110```
111
112  ```
113  /* xxx.css */
114  .container {
115    flex-direction: column;
116    justify-content: center;
117    align-items: center;
118    width: 100%;
119  }
120  .box{
121    width: 200px;
122    height: 200px;
123    background-color: #ff0000;
124    margin-top: 30px;
125  }
126  .buttonBox{
127    margin-top: 30px;
128    width: 250px;
129    justify-content: space-between;
130  }
131  button{
132    background-color: #8e8b89;
133    color: white;
134    width: 100px;
135    height: 40px;
136    font-size: 24px;
137  }
138  ```
139
140  ```
141  // xxx.js
142  import prompt from '@system.prompt';
143  export default{
144    data:{
145      animation:'',
146    },
147    onInit(){
148    },
149    onShow(){
150      var options = {
151        duration: 1500,
152        easing: 'friction',
153        delay: 500,
154        fill: 'forwards',
155        iterations: 2,
156        direction: 'normal',
157      };
158      var frames = [
159        {transform: {translate: '-120px -0px'}, opacity: 0.1, offset: 0.0},
160        {transform: {translate: '120px 0px'}, opacity: 1.0, offset: 1.0}
161      ];
162      this.animation = this.$element('idName').animate(frames, options);
163      // handle finish event
164      this.animation.onfinish = function(){
165        prompt.showToast({
166          message: "The animation is finished."
167        });
168      };
169      // handle cancel event
170      this.animation.oncancel = function(){
171        prompt.showToast({
172          message: "The animation is canceled."
173        });
174      };
175      // handle repeat event
176      this.animation.onrepeat = function(){
177         prompt.showToast({
178            message: "The animation is repeated."
179         });
180      };
181    },
182    start(){
183      this.animation.play();
184    },
185    cancel(){
186      this.animation.cancel();
187    }
188  }
189  ```
190
191  ![img](figures/animationapi-4.gif)
192
193## getBoundingClientRect
194
195getBoundingClientRect(): \<Rect>
196
197Obtains the size of the element and its position relative to the window.
198
199- Return value
200
201  **Table 5** Rect<sup>6+</sup>
202
203  | Attribute | Type   | Description                                                  |
204| --------- | ------ | ------------------------------------------------------------ |
205  | width     | number | Width of an element.                                         |
206  | height    | number | Height of an element.                                        |
207  | left      | number | Offset between the left boundary of the element and the window. |
208  | top       | number | Offset between the upper boundary of the element and the window. |
209
210- Example
211
212  ```
213  // xxx.js
214  var rect = this.$element('id').getBoundingClientRect();
215  console.info(`current element position is ${rect.left}, ${rect.top}`);
216  ```
217
218## createIntersectionObserver
219
220createIntersectionObserver(param?:  ObserverParam): Observer
221
222Gets notified of the visibility of an element on the current page.
223
224- Parameters
225
226  | Name  | Type          | Mandatory | Description                    |
227| ----- | ------------- | --------- | ------------------------------ |
228  | param | ObserverParam | -         | Obtains the observer callback. |
229
230  **Table 6** ObserverParam<sup>6+</sup>
231
232  | Attribute | Type          | Description                                                  |
233| --------- | ------------- | ------------------------------------------------------------ |
234  | ratios    | Array\<number> | When the component is out of the range or is less than the range, the observer callback is triggered. |
235
236- Return value
237
238  **Table 7** Methods supported by the Observer object<sup>6+</sup>
239
240  | Name      | Parameter          | Description                                                  |
241| --------- | ------------------ | ------------------------------------------------------------ |
242  | observe   | callback: function | Subscribes to events of the observed object. The callback method is called when the value is greater than or less than the threshold. |
243  | unobserve | -                  | Unsubscribes from events of the observed object.             |
244
245- Example
246
247  ```
248  // xxx.js
249  let observer = this.$element('broad').createIntersectionObserver({
250    ratios: [0.2, 0.5], // number
251  });
252
253  observer.observe((isVisible, ratio)=> {
254      console.info('this element is ' + isVisible + 'ratio is ' + ratio)
255  })
256
257  observer.unobserve()
258  ```