Angular 角度2+;,侧边栏的动画和css控制变换
我有一个侧边栏,它有一个菜单图标,按下图标它会将侧边栏移出视图,并调整主要内容的宽度。但我也希望它在浏览器窗口宽度低于500px时自动移出视图,在高于500px时自动跳出,同时保持用户仍然可以打开和关闭侧边栏的能力,我该怎么做?我愿意使用css类、所有ts逻辑或两者的组合来完成这一切,我只是不知道怎么做,我的代码是:Angular 角度2+;,侧边栏的动画和css控制变换,angular,css-animations,angular-animations,Angular,Css Animations,Angular Animations,我有一个侧边栏,它有一个菜单图标,按下图标它会将侧边栏移出视图,并调整主要内容的宽度。但我也希望它在浏览器窗口宽度低于500px时自动移出视图,在高于500px时自动跳出,同时保持用户仍然可以打开和关闭侧边栏的能力,我该怎么做?我愿意使用css类、所有ts逻辑或两者的组合来完成这一切,我只是不知道怎么做,我的代码是: <div class="sidenav" [@slideInOut]="menuState"> <span (click)="toggleMenu()" cl
<div class="sidenav" [@slideInOut]="menuState">
<span (click)="toggleMenu()" class="ham-menu"><b>☰</b></span>
</div>
<div [@contentMargin]="contentWidth" class="content">
content
</div>
使用component.ts动画部分:
animations: [
trigger('slideInOut', [
state('out', style({
transform: 'translate3d(0px, 0, 0)'
})),
state('in', style({
transform: 'translate3d(-200px, 0, 0)'
})),
transition('in => out', animate('400ms ease-in-out')),
transition('out => in', animate('400ms ease-in-out'))
]),
trigger('contentMargin', [
state('full', style({
marginLeft: '210px',
width: 'calc(100% - 210px)'
})),
state('reduced', style({
marginLeft: '10px',
width: 'calc(100% - 10px)'
})),
transition('reduced => full', animate('400ms ease-in-out')),
transition('full => reduced', animate('400ms ease-in-out'))
]),
]
和逻辑:
menuState = 'out';
contentWidth = 'full';
toggleMenu() {
this.menuState = this.menuState === 'out' ? 'in' : 'out';
this.contentWidth = this.contentWidth === 'full' ? 'reduced' : 'full';
}
然后根据屏幕宽度自动调整大小,我在下面尝试过,但没有成功
@media (max-width: 499.9px) {
.sidenav {
transition: 400ms ease-in-out;
transform: translate3d(-200px, 0, 0);
}
}
@media (min-width: 500px) {
.sidenav {
transition: 400ms ease-in-out;
transform: translate3d(0px, 0, 0);
}
}
一种简单的方法是使用Angular的HostListener装饰器检测窗口宽度的变化,并添加所需的逻辑 您只需将其添加到组件中即可。ts:
@HostListener('window:resize', ['$event'])
onResize(event) {
console.log("Width: " + event.target.innerWidth);
this.windowWidth = event.target.innerWidth;
if(this.windowWidth<500) {
this.menuState = 'in';
} else {
this.menuState = 'out';
}
}
@HostListener('window:resize',['$event']))
onResize(事件){
log(“宽度:”+event.target.innerWidth);
this.windowWidth=event.target.innerWidth;
if(this.windowwidth)查看。您可以使用捕获断点更改,然后显示/隐藏Sidenav。我建议使用ngIf隐藏/显示Sidenav。
@HostListener('window:resize', ['$event'])
onResize(event) {
console.log("Width: " + event.target.innerWidth);
this.windowWidth = event.target.innerWidth;
if(this.windowWidth<500) {
this.menuState = 'in';
} else {
this.menuState = 'out';
}
}