Angular transition自动复位问题:实现index增减时div左右滑动效果
问题原因
- 当前定义的动画仅指定了过渡过程的最终样式,没有做状态持久化,Angular在动画执行完毕后会自动清除临时添加的动画样式,因此会回弹到初始状态。
- 现有布局没有将所有标题项横向排列,也没有限制父容器的可视区域,即使动画保留样式也无法实现正常的滑动切换效果。
- 下一页按钮的禁用逻辑存在边界错误,最大可选索引为
imageTitles.length - 1,原写法会出现索引越界问题。
修改方案
1. 调整动画定义
使用state绑定索引对应的偏移状态,动画执行后会自动保留对应状态的样式,不会回弹:
animations: [ trigger('animSlider', [ // 定义通用状态,根据传入的offset参数设置平移距离 state('*', style({ transform: 'translateX(-{{offset}}%)' }), { params: { offset: 0 } }), // 索引递减(切上一页)时的过渡动画 transition(':decrement', [ animate('300ms ease-out') ]), // 索引递增(切下一页)时的过渡动画 transition(':increment', [ animate('300ms ease-out') ]), ]), ]
2. 修改HTML模板
传入动画所需的偏移参数,同时调整标题项的定位属性:
<figcaption class="image-overlay"> <button (click)="onPrevious(image)" mat-icon-button class="slider-button prev" color="primary" [disabled]="image.index === 0"><mat-icon>navigate_before</mat-icon></button> <!-- 绑定动画值与偏移参数 --> <div [@animSlider]="{value: image.index, params: {offset: image.index * 100}}" class="image-title-choices"> <!-- 每个标题项按索引横向排列 --> <div *ngFor="let title of imageTitles; let i = index" class="image-title-choice-hold" fxLayout="row" fxLayoutAlign="center" [style.left.%]="i * 100"> <span>{{ title }}</span> </div> </div> <!-- 修正下一页按钮禁用逻辑 --> <button (click)="onNext(image)" [disabled]="image.index === imageTitles.length - 1" mat-icon-button class="slider-button next" color="primary"><mat-icon>navigate_next</mat-icon></button> </figcaption>
3. 补充对应CSS样式
.image-title-choices { position: relative; width: 100%; /* 可根据实际业务调整高度 */ height: 40px; overflow: hidden; } .image-title-choice-hold { position: absolute; top: 0; width: 100%; height: 100%; }
内容的提问来源于stack exchange,提问作者James Guerra
相关产品推荐
相关产品推荐

