【问题标题】:Angular animate element while changing position?改变位置时的角度动画元素?
【发布时间】:2017-08-28 06:02:23
【问题描述】:

我正在尝试为我的 Angular 项目中的 div 设置动画,以便它在屏幕上移动。 div 是相对定位的(因为有多个元素),但是当我应用动画时,我将其更改为固定(因为我无法从相对状态获取确切位置,也无法发送参数)。

问题在于,位置恰好在过渡时间的一半处应用于动画。因此,如果我将其设置为 5 秒,则在 2.5 秒时,div 将从相对变为固定。这会导致动画随机跳跃并在 2.5 秒后从不同的位置开始动画。这是正常行为吗?

我创建了一个(基本)plunkr 来说明我的意思:

https://plnkr.co/edit/kSnGSqZUIkMn7y3Vv2bm?p=preview

HTML:

  <div style="position:relative; top:0; left:0; width:20%; height:20%"
  [@routerTransition]="animation">
    <h2>Home</h2> 
  </div>
  <button (click)="animateBox()"> Animate </button>

还有动画:

return trigger('routerTransition', [
    state('*', style({   })),
    transition('* => move', animate(5000, style({position: 'fixed', left: "500px",  top: "500px",  })))

我可以通过在动画开始时应用 position: fixed 来解决这个问题,例如:

state('move', style({ position:"fixed"  })),

然而,元素不会从它的起始位置移动,而是从固定位置移动。

有没有办法从相对位置开始动画,然后将其动画到不同(固定)位置,同时避免中途“跳跃”?

【问题讨论】:

  • 我不知道怎么做,但我还是不明白你到底想要什么?
  • 像这样的相对动画难以置信地难以编码,并且可能超出了您尝试的范围。这是可能的,但是对于一个简单的动画需要相当多的复杂代码。
  • 不能真正解决您的问题......但我会说 - 一般来说,动画固定位置元素很容易出现错误。动画“顶部”和“左侧”通常是,但更多的是固定位置。除了一些非常特殊的情况,我总是选择动画变换 (translate3d(x,y,z)) 来代替

标签: angular angular2-animation


【解决方案1】:

这是解决此问题的最佳方法,只需检测滚动的时间 超过您想要的像素并添加一些变量 true 或 false 在你检测到你可以添加一些 CSS 类之后,就是这样。

一些代码示例。

yourComponent.html

<md-card  [class.fixed]="navIsFixed">
    <img src="{{Product.image_url}}" style="width:100%;" alt="">
</md-card>

yourComponent.css

.fixed {
  position: fixed;
  width: 250px;
  top: 20px;
  z-index: 2;
}

yourComponent.ts

import { Component, OnInit, HostListener, Inject } from "@angular/core";
import { DOCUMENT } from '@angular/platform-browser';

@Component({
  selector: 'app-client-product-prev',
  templateUrl: './client-product-prev.component.html',
  styleUrls: ['./client-product-prev.component.css'],
})

export class yourComponent implements OnInit {

  public navIsFixed: Boolean = false;
  
  constructor(){}
  
  ngOnInit() {

  }


  @HostListener("window:scroll", [])
  onWindowScroll() {
    const number = this.document.body.scrollTop;
    if (number > 300) {
      this.navIsFixed = true;
      console.log(number);
    } else if (this.navIsFixed && number < 300) {
      this.navIsFixed = false;
    }
    
  }




}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-27
    • 2014-04-27
    • 2017-04-12
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    相关资源
    最近更新 更多