繁体   English   中英

Angular 8 - 如何在桌面和移动设备上使用不同的值触发 animation?

[英]Angular 8 - how to trigger animation with different values on Desktop and Mobile?

我正在完成我的 webApp 并使其具有响应性。 我遇到了最后一个我似乎无法解决的问题!

我有一个 animation,用于类似弹出框的元素, Right Left

在移动设备上,没有足够的空间,所以我将在 Input 字段下方打开该元素,而不是在侧面,所以我需要一个从Bottom滑动到Top的 animation 。

这是我用于桌面屏幕的默认 animation 的代码:

animations: [
    trigger("slideInOut", [
      transition(":enter", [
        style({ transform: "translateX(60%)", opacity: 0 }),
        animate(
          "300ms ease-in",
          style({ transform: "translateX(0%)", opacity: 1 })
        ),
      ]),
      transition(":leave", [
        animate(
          "300ms ease-in",
          style({ transform: "translateX(60%)", opacity: 0 })
        ),
      ]),
    ]),
  ]

我唯一想改变的是transform的 3 个值

对于移动设备,我需要:

translateY(60%)
translateY(0%)
translateY(60%)

所以基本上只需将 X 轴与 Y 轴交换!

我怎样才能做到这一点? 如果无法更改这些值,即使禁用 animation for mobile 也可以!

我想到了一个解决方案,但很脏,很脏,基本上我会创建一个我的“popover-like DIV”的副本,然后在他们两个上,拍一个 class:例如:

.mobile

.desktop

然后,基于媒体查询,我会显示一个或另一个,最后在每个查询上,我会附加一个不同的 animation 触发器,我会在我的组件中声明两个触发器,一个用于 Y 轴,一个用于X 轴。 这应该可行,但我根本不喜欢它!

我遇到了同样的问题并设法解决了这个问题。 不确定这是否是最好的解决方案,但它有效。

所以在组件中我听页面宽度大小。 不要忘记从构造函数中调用监听器,否则只有在调整屏幕大小时才会触发。

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss'],
  animations: [
    trigger('slideInOut', [
      transition(':enter', [
        style({ transform: '{{translateType}}(-100%)' }),
        animate('900ms ease-in', style({ transform: '{{translateType}}(0%)' })),
      ]),
      transition(':leave', [animate('700ms ease-in', style({ transform: '{{translateType}}(-100%)' }))]),
    ]),
  ],
})
export class MyComponent {
  screenWidth: number;

  @HostListener('window:resize', ['$event'])
  onResize() {
    this.screenWidth = window.innerWidth;
  }

  constructor() {
    this.onResize();
  }

  getAnimationTransformValue(): string {
    return this.screenWidth <= 800 ? 'translateY' : 'translateX';
  }
}

在您的 html 模板中,我使用以下语法传入样式转换值。

<div  [@slideInOut]="{ value: true, params: {translateType: getAnimationTransformValue() }}">
  Content
</div>

在我的例子中,我使用移动查询来选择 div 的 class,然后在 animation 查询中,根据类编写不同的动画。 通过这种方式,我可以使用非常独立的动画,而无需传递参数。

我的组件.html

<div class="dp-a" [@fadeOut]>
    <div class="d0" (click)="closePanel()"></div>
        <div [ngClass]="mobileQuery.matches? 'd1':'d1-desktop'"><!--HERE class query-->

我的组件.ts

query('.d1', // mobile class
    animate('0.3s ease-in', style({ transform: 'translateY(0%)' })), 
    { optional: true }
),
query('.d1-desktop', // desktop class
    animate('0.2s ease-out', style({ transform: 'scale(1)' })), 
    { optional: true }
)

重要提示:不要忘记{ optional: true } 由于选择了 class,因此在[ngClass]中需要三元运算符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM