You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular动画实现:点击按钮使div每次向右移动指定像素

在Angular中实现点击触发元素逐次右移动画

要实现你给出的jQuery同款点击逐次右移效果,Angular里有两种常用方案,下面分别演示:

方案一:使用Angular官方动画模块(@angular/animations)

适合需要复杂动画逻辑、多状态管理的场景。

1. 先导入动画模块

在你的应用模块(如AppModule)中引入BrowserAnimationsModule:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  imports: [
    // 其他必要模块(如BrowserModule)
    BrowserAnimationsModule
  ]
})
export class AppModule { }

2. 组件中定义动画与逻辑

import { Component } from '@angular/core';
import { trigger, transition, animate, style } from '@angular/animations';

@Component({
  selector: 'app-move-box',
  template: `
    <button (click)="moveBox()">点击移动</button>
    <div [@moveRight]="{ value: currentLeft, params: { left: currentLeft } }" class="box"></div>
  `,
  styles: [`
    .box {
      position: absolute;
      width: 50px;
      height: 50px;
      background: blue;
      left: 0;
      top: 50px;
    }
  `],
  animations: [
    trigger('moveRight', [
      transition('* => *', [
        animate('300ms ease-out', style({ left: '{{left}}px' })),
      ]),
    ])
  ]
})
export class MoveBoxComponent {
  currentLeft = 0;
  // 每次移动的步长
  step = 25;

  moveBox() {
    this.currentLeft += this.step;
  }
}

方案二:使用CSS过渡(更轻量)

如果只是基础的位移需求,用CSS过渡配合Angular样式绑定更简单,无需额外引入动画模块:

import { Component } from '@angular/core';

@Component({
  selector: 'app-move-box',
  template: `
    <button (click)="moveBox()">点击移动</button>
    <div class="box" [style.left.px]="currentLeft"></div>
  `,
  styles: [`
    .box {
      position: absolute;
      width: 50px;
      height: 50px;
      background: blue;
      left: 0;
      top: 50px;
      transition: left 300ms ease-out;
    }
  `]
})
export class MoveBoxComponent {
  currentLeft = 0;
  step = 25;

  moveBox() {
    this.currentLeft += this.step;
  }
}

两种方案都能实现点击按钮时div每次向右移动25px的效果,可按需选择:

  • 若需要多状态切换、动画回调等复杂逻辑,选方案一;
  • 若只是简单位移,方案二更简洁高效。

内容的提问来源于stack exchange,提问作者Piotr Deja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 09:51:04