我正在尝试使用下拉列表创建一个垂直菜单。我现在通过在CSS中使用'hover'来工作但是我想这样做以便用户可以点击下拉菜单,即使用户没有将鼠标悬停在子菜单上,子菜单也会保持打开状态。
我遇到的问题是,当我单击Statistics下拉列表时,它实际上会进入方法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;
}
感谢您的帮助,这一直困扰着我的方式!
答案 0 :(得分:2)
尽量避免从Angular2中的代码直接访问DOM。而是使用像ngStyle
:
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>