js 中判断 transform translation 结束
时间: 2024-02-23 19:59:29 浏览: 31
在 JavaScript 中,可以使用 `transitionend` 事件来判断 CSS 动画的结束。但是,`transitionend` 事件只适用于 CSS 的 `transition` 属性,对于 `transform` 属性的变化,需要使用 `transitionend` 事件的兼容性库或者手动判断。
其中,判断 `transform` 的 `translation` 是否结束,可以通过以下两种方式实现:
1. 使用 `getComputedStyle` 方法获取元素的 `transform` 属性值,判断 `translateX` 和 `translateY` 是否为目标值。示例代码如下:
```javascript
const element = document.getElementById('my-element');
const computedStyle = window.getComputedStyle(element);
const transform = computedStyle.getPropertyValue('transform');
const matrix = new DOMMatrixReadOnly(transform);
const currentX = matrix.m41;
const currentY = matrix.m42;
if (currentX === targetX && currentY === targetY) {
// 动画结束,执行操作
}
```
在上面的代码中,`targetX` 和 `targetY` 分别为 `translateX` 和 `translateY` 的目标值。通过比较当前值和目标值,判断动画是否结束。
2. 使用 `requestAnimationFrame` 方法实现动画帧的循环,判断 `translateX` 和 `translateY` 是否达到目标值。示例代码如下:
```javascript
const element = document.getElementById('my-element');
const targetX = 100;
const targetY = 100;
function animate() {
const transform = element.style.transform;
const matrix = new DOMMatrixReadOnly(transform);
const currentX = matrix.m41;
const currentY = matrix.m42;
if (currentX === targetX && currentY === targetY) {
// 动画结束,执行操作
} else {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
```
在上面的代码中,使用 `requestAnimationFrame` 方法实现动画帧的循环,判断当前值和目标值是否相等,如果不相等则继续执行动画帧的循环,直到达到目标值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)