我正在尝试制作带有下拉菜单的垂直菜单。我目前通过在 CSS 中使用“悬停”来使其工作,但我想让用户可以单击下拉菜单,并且即使用户没有将鼠标悬停在其上,子菜单也将保持打开状态。
我遇到的问题是,当我单击“统计”下拉列表时,它实际上会将其放入方法 showStatMenu() 中,但子菜单实际上不会打开/变得可见。这让我假设 showStatMenu() 中的代码对于 Angular 2 实际更改 CSS 来说是错误的。
*是的,我意识到 showStatMenu() 不会切换打开和关闭,我只是希望它先打开,然后担心稍后切换它打开和关闭
HTML
<div class="dashboard">
<ul class="mainmenu">
<li><a (click)="showStatMenu()">Statistics <span class="right"><i class="fa fa-angle-down"></i></span></a>
<ul class="submenu" id='stat'>
<li *ngFor="let dashboard of dashboards"><a class="indent" *ngIf="dashboard.id == 1" (click)="gotoDetail(dashboard)">Team</a></li>
<li *ngFor="let dashboard of dashboards"><a class="indent" *ngIf="dashboard.id == 2" (click)="gotoDetail(dashboard)">Player</a></li>
</ul>
</li>
</ul>
</div>
TS
import { Component, OnInit } from '@angular/core';
import { Dashboard } from './dashboard';
import { DashboardService } from './dashboard.service';
import { Router } from '@angular/router';
@Component({
moduleId: module.id,
selector: 'my-dashboard',
templateUrl: 'dashboard.component.html',
styleUrls: [ 'dashboard.component.css']
})
export class DashboardComponent implements OnInit {
// Took out init method and other irrelevant code
showStatMenu(){
document.getElementById('stat').style.display = 'block';
document.getElementById('stat').style.width = '200px';
}
}
CSS(可能有用,但我不认为这是问题)
html, body {
font-family: Arial, Helvetica, sans-serif;
}
.navigation {
width: 300px;
}
.mainmenu, .submenu {
list-style: none;
padding: 0;
margin: 0;
width: 200px;
}
.mainmenu a {
display: block;
background-color: #d7dfea;
text-decoration: none;
padding: 10px;
color: #000;
}
.mainmenu a:hover {
background-color: #5a98fc;
cursor: hand;
}
/*.mainmenu li:hover .submenu {
display: block;
max-height: 200px;
}*/ /*Hiding hover option*/
.submenu a {
background-color: #9a9c9e;
text-indent: 20px;
}
.submenu a:hover {
background-color: #55d3ed;
cursor: hand;
}
.submenu {
overflow: hidden;
max-height: 0;
-webkit-transition: all 0.5s ease-out;
}
.right{
float: right;
}
感谢您的帮助,这个问题已经困扰我很长时间了!
最佳答案
尽量避免从 Angular2 中的代码直接访问 DOM。而是使用像 ngStyle
这样的绑定(bind)和指令:
export class DashboardComponent implements OnInit {
showStat:boolean = false;
}
<div class="dashboard">
<ul class="mainmenu">
<li><a (click)="showStat = !showStat">Statistics <span class="right"><i class="fa fa-angle-down"></i></span></a>
<ul class="submenu" [ngStyle]="{'display': showStat ? 'block' : 'none, 'width': showStat ? '200px' : '0'}" >
<li *ngFor="let dashboard of dashboards"><a class="indent" *ngIf="dashboard.id == 1" (click)="gotoDetail(dashboard)">Team</a></li>
<li *ngFor="let dashboard of dashboards"><a class="indent" *ngIf="dashboard.id == 2" (click)="gotoDetail(dashboard)">Player</a></li>
</ul>
</li>
</ul>
</div>
关于html - 如何从 Angular 2 组件中更改 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40295832/