如何在鼠标悬停时向菜单项添加和删除类

时间:2018-11-13 04:07:49

标签: javascript angular typescript

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

menu-bar.component.html

where

menu-bar.component.ts

let in

4 个答案:

答案 0 :(得分:2)

使用CSS :hover 伪类,它将起作用。

css:

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

答案 1 :(得分:0)

您可以使用*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>

menu-bar.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-menu-bar',
  templateUrl: './menu-bar.component.html'
})
export class MenuBarComponent implements OnInit {
 menuItems: any = [];
 constructor() { 
  this.menuItems = [{name: 'link1', name: 'link2'}]
 }
  ngOnInit() {
  }

  changeStyle(menu) {
    menu.hovered = !menu.hovered;
 }
}

答案 2 :(得分:0)

由于具有使用同一功能的多个元素,因此需要一些标识来标识需要添加类的导航项。

请注意此更改:

(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;
    }
  }
}

这是它的演示:https://stackblitz.com/edit/angular-jvk15a

答案 3 :(得分:0)

如果您仅用于更改样式,我认为可以在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
}

如果希望这会有所帮助。