Javascript 如何在鼠标上方的菜单项中添加和删除类

Javascript 如何在鼠标上方的菜单项中添加和删除类,javascript,angular,typescript,Javascript,Angular,Typescript,当鼠标移到菜单项上时,我想在该菜单项上添加和删除“hover open”类。我尝试的代码是,当鼠标停留在单个菜单项上时,将该类添加到所有菜单项 menu-bar.component.html 您可以使用*ngFor <ul> <li *ngFor="let menu of menuItems" (mouseover)="changeStyle(menu)" (mouseout)="changeStyle(menu)" [className]="menu.hovered ?

当鼠标移到菜单项上时,我想在该菜单项上添加和删除“hover open”类。我尝试的代码是,当鼠标停留在单个菜单项上时,将该类添加到所有菜单项

menu-bar.component.html
您可以使用
*ngFor

<ul>
  <li *ngFor="let menu of menuItems" (mouseover)="changeStyle(menu)" (mouseout)="changeStyle(menu)" [className]="menu.hovered ? 'hover-open nav-item':'nav-item'"><a href="#">{{menu.name}}</a></li>
</ul>

因为有多个元素使用同一个函数,所以需要一些标识来标识需要添加类的导航项

请注意这一变化:

(mouseover)="changeStyle('link1','in')" [class.hover-open]="hovered === 'link1'"  (mouseout)="changeStyle('link1','out')" class="nav-item"
我改变了什么

(mouseover)="changeStyle('link1','in')" //passing unique id for each li
(mouseout)="changeStyle('link1','out')" // passing out to remove the class
[class.hover-open]="hovered === 'link1'" //checking if link is link1
 then add the class other wise remove
你可以这样做

<ul>
<li id="link1" (mouseover)="changeStyle('link1','in')" [class.hover-open]="hovered === 
'link1'"  (mouseout)="changeStyle('link1','out')" 
class="nav-item"><a href="#">Link 1</a>
</li>
<li id="link1" (mouseover)="changeStyle('link2','in')" 
[class.hover-open]="hovered === 'link2'" (mouseout)="changeStyle('link2','out')"  
class="nav-item">
<a href="#">Link 2</a></li>
<li id="link1" (mouseover)="changeStyle('link3','in')" [class.hover-open]="hovered === 'link3'" (mouseout)="changeStyle('link3','out')"  class="nav-item"><a href="#">Link 3</a></li>
<li id="link1" (mouseover)="changeStyle('link4','in')" 
[class.hover-open]="hovered === 'link4'" (mouseout)="changeStyle('link4','out')" 
 class="nav-item"><a href="#">Link 4</a></li>
</ul>



export class AppComponent {     
  hovered = '';

  changeStyle(linkName, typeOfMove) {
    if (typeOfMove === 'out') {
      this.hovered = '';
    } else {
      this.hovered = linkName;
    }
  }
}
导出类AppComponent{ 悬停=“”; 变更样式(链接名称、移动类型){ if(typeOfMove==='out'){ 这个。悬停=“”; }否则{ this.hovered=linkName; } } }

下面是它的演示:

使用CSS:hoverPseudo类,它就可以工作了

css:

li: hover{
          write down style which you want to apply
}

我认为这段代码可以在css上完成,如果你只是用来改变样式的话

li { // default style for unhovered }
li:hover { // style when hover }
如果您想通过DOM访问它。也许你可以试试这个

changeStyle(event) {
  const klass = event.classList

  if (klass.contains("hover-open"))
    // remove class here
  else // add the class here
}

如果希望有帮助的话。

使用css而不是javascipt。。。
li: hover{
          write down style which you want to apply
}
li { // default style for unhovered }
li:hover { // style when hover }
changeStyle(event) {
  const klass = event.classList

  if (klass.contains("hover-open"))
    // remove class here
  else // add the class here
}