Angular中如何读取带transition的元素实时样式及判断过渡状态?
解决方案
1. 获取过渡中的实时宽度值
使用window.getComputedStyle()方法可以拿到元素当前实际渲染的CSS属性值,包括过渡动画过程中的中间状态,这是element.style.width做不到的:
const currentWidth = window.getComputedStyle(this._expBar.nativeElement).width;
这个值会随着过渡动画的进行实时更新,比如从50%过渡到100%的过程中,你能拿到"60%"、"85%"这类中间值。
2. 判断过渡动画是否正在进行
最可靠的方式是通过监听过渡相关事件维护状态:
- 监听
transitionstart事件:过渡开始时标记状态为true - 监听
transitionend事件:过渡结束时将状态设为false
示例代码:
private isTransitioning = false; ngAfterViewInit() { const bar = this._expBar.nativeElement; bar.addEventListener('transitionstart', (event) => { // 仅针对width属性的过渡做标记 if (event.propertyName === 'width') { this.isTransitioning = true; } }); bar.addEventListener('transitionend', (event) => { if (event.propertyName === 'width') { this.isTransitioning = false; } }); }
如果担心过渡被中断(比如动画过程中再次修改宽度),还可以监听transitioncancel事件同步更新状态。
3. 直接在宽度达到100%时触发函数(最优方案)
既然你的需求是宽度抵达100%时执行函数,不需要实时检测宽度——因为你是主动将宽度修改为100%,过渡结束时就意味着已到达目标值,直接监听transitionend即可:
ngAfterViewInit() { const bar = this._expBar.nativeElement; bar.addEventListener('transitionend', (event) => { if (event.propertyName === 'width') { this.targetFunction(); } }); } private targetFunction() { // 这里写你需要执行的业务逻辑 }
内容的提问来源于stack exchange,提问作者user13002098
相关产品推荐
相关产品推荐

