【问题标题】:How to modify CSS variable in an angular animation state如何在角度动画状态下修改 CSS 变量
【发布时间】:2021-09-16 07:35:24
【问题描述】:

我正在创建一个“可拖动”组件,它可以在页面上移动并在销毁时播放动画。我正在将组件主机的style.transform 属性设置为translate3d 以更改其在文档上的位置:

@Component({
    selector: 'app-window',
    templateUrl: './window.component.html',
    styleUrls: ['./window.component.scss'],
    animations: [
        trigger('WindowAnimation', [
            state('void', style({ 
                opacity: '0',
                transform: 'scale(0)', // host is `display: block`
            })),
            transition('* => void', [
                animate('1000ms ease-out')
            ])
        ])
    ]
})
export class WindowComponent implements OnInit {
    @Input('left') public left: number = 0;
    @Input('top') public top: number = 0;
    @HostBinding('@WindowAnimation') animation: boolean = true;
    @HostBinding('style.transform') get hostTransform(): string {
        return `translate3d(${this.left}px, ${this.top}px, 0px)`;
    }
}

问题是动画的scale 部分没有播放。我认为这是因为组件主机已经具有主机绑定给定的style.transform 属性:如果我删除style.transform 主机绑定,动画可以正确播放,但我对组件位置的控制松了。然后,我尝试使用 CSS 变量通过将主机绑定替换为以下内容来解决问题:

@HostBinding('style.transform') get hostTransform(): string {
    return `translate3d(${this.left}px, ${this.top}px, 0px) scale(var(--host-scale, 1))`;
}

但是,我需要在动画期间修改--host-scale CSS 变量。我尝试过这样的事情但没有成功:

// [...]
state('void', style({ 
    opacity: '0',
    '--host-scale': `0`, // fails at runtime with '"--host-scale" is not a supported CSS property for animations'
})),
// [...]

是否可以告诉 Angular 将参数“添加”到已经存在的 style.transform 属性或在动画期间更改 CSS 变量的值?

【问题讨论】:

    标签: css angular animation


    【解决方案1】:

    不确定这是否有帮助,但也许值得一试

    我自己没有处理过这个问题,但我可以想象你必须改变你触发这整个事情的方式。我所做的是将动画附加到一个 css 类,然后在组件上切换它。

    css:

    .highlight {
        animation-name: highlightComponent;
        animation-duration: 5s;
    }
    
    @keyframes highlightComponent {
        from {
            background-color: rgba(14, 231, 255, 0.7);
        }
        to {
            background-color: rgb(255, 255, 255);
        }
    }
    

    ts:

      highlightChanges(elementId: string) {
          document.getElementById(elementId).classList.add('highlight')
      }
    

    【讨论】:

    • 我的动画效果和你的不一样,但也许可以作为灵感
    • 我刚刚尝试过(通过将::ng-deep 属性添加到css 块并手动将类添加到组件主机)它似乎不起作用:如果我为transform 设置动画属性,则 translate3d 属性将被覆盖且不再应用。如果我改为为--host-scale CSS 变量设置动画,动画似乎可以工作,但没有进行插值:它只显示两个不同的状态 scale(1) 和 scale(1)。另外,我认为在销毁组件时我不能轻易播放动画(如角度动画中的* => void 过渡)。
    • 这是凝灰岩,也许这篇文章可以帮助你。 angular.io/guide/animations#triggering-the-animation
    猜你喜欢
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多