Angular中使用@ViewChild操作DOM实现CSS3动画效果

首先,使用命令ng generate component my-transition创建一个my-transition的组件,创建完成后,开始编写代码:

  • my-transition.component.html代码部分:
    这部分主要是建立一个布局结构
<div class="container">
    内容区域
    <button *ngIf="isShow" (click)="showSlider()">打开侧边栏</button>
    <button *ngIf="!isShow" (click)="hiddenSlider()">关闭侧边栏</button>
</div>
<div #slider class="slider">
    <ul>
        <li>首页</li>
        <li>机构管理</li>
        <li>部门管理</li>
        <li>权限管理</li>
        <li>个人中心</li>
    </ul>
</div>

  • my-transition.component.less代码部分:
    右侧菜单栏使用position脱离文档流,使用translate去控制右侧菜单栏的移动。
.slider {
    position: absolute;
    width: 200px;
    height: 100vh;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: rgba(0,0,0,.5);
    transform: translate(0,0);
    transition: all 2s;
    ul {
        width: 100%;
        padding: 0;
    }
    ul li {
        display: block;
        height: 50px;
        text-align: center;
        line-height: 50px;
        color: rgba(255,255,255,.8);
        border-bottom: 1px solid #e5e5e5;
    }
}

注意,同时需要修改下全局的CSS样式文件内容:
让整个文档流平铺在可视区内,不展示横向滚动条。


image.png
  • my-transition.component.ts代码部分:
    这部分就是单纯的去获取DOM元素然后去操作的,可以将按钮分成两个提出来写,也可以使用switch去合并在一个按钮中去写。都能实现相应的效果。
import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-my-transition',
  templateUrl: './my-transition.component.html',
  styleUrls: ['./my-transition.component.less']
})
export class MyTransitionComponent implements OnInit {

  public isShow: boolean = false; //控制右侧侧边栏

  @ViewChild('slider') slider: any; //获取DOM元素

  constructor() { }

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {


  }

  showSlider() {
    this.isShow = !this.isShow;
    this.slider.nativeElement.style.transform = "translate(0,0)"
  }
  hiddenSlider(){
    this.isShow = !this.isShow;
    this.slider.nativeElement.style.transform = "translate(200px,0)"
  }
}

image.png

image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 纯CSS3制作二级菜单特效 基础掌握知识:1.boder-radis圆角的制作 2.linear-gradient...
    Iris_mao阅读 9,394评论 2 17
  • 16宿命:用概率思维提高你的胜算 以前的我是风险厌恶者,不喜欢去冒险,但是人生放弃了冒险,也就放弃了无数的可能。 ...
    yichen大刀阅读 11,276评论 0 4
  • 公元:2019年11月28日19时42分农历:二零一九年 十一月 初三日 戌时干支:己亥乙亥己巳甲戌当月节气:立冬...
    石放阅读 11,803评论 0 2