用NgClass悬停一个div

问题描述 投票:2回答:2

我试图用Angular ngClass指令对div进行悬停效果。在模板文件中,我有一个带有“list-item-container”类的div元素,它包含一个带有“list-item”类的div,它使用* ngFor指令进行迭代。在“list-item”div元素中我有三个带有“list-item-column”类的div,它们像一个带有内联显示的表行一样水平放置。在带有“list-item”类的div中,我放置了一个mouseenter和mouseleave事件监听器,它在我的.ts中调用hoverListItem()文件.hoverListItem()函数将listItemHovered变量的值更改为true或false。在“list-item”类中,我有一个ngClass指令,它根据listItemHovered boolean的值触发css类'list-item-highlight'然后将值更改为背景为不同的颜色。

我面临的问题是,当鼠标指针悬停在“list-item”div上时,我的所有“list-item”div都会受到影响,而不是我正在悬停的那个。如何解决这个问题呢?

.html文件

<div class="list-item-container">
      <ng-container *ngFor="let opportunity of dealService.opportunities">
        <div [ngClass]="{'list-item-highlight': listItemHovered}" class="list-item" (mouseenter)="hoverListItem()"
             (mouseleave)="hoverListItem()"
             (click)="selectOpportunity(opportunity)">
          <div
            class="list-item-column">{{opportunity.account?.name === null ? "N/A" : opportunity.account.name}}</div>
          <div class="list-item-column">{{opportunity.requirementTitle}}</div>
          <div class="list-item-column">{{opportunity.salesValue | number: '1.0-2'}}</div>
        </div>
      </ng-container>
    </div>

.css文件

.list-item-container{
  overflow: auto;
  width: 100%;
  max-height: 500px;
}
.list-item{
  font-size: 15px;
  border-radius: 10px ;
  margin-top: 5px;
  height: 50px;
  background: lightgray;
  color: black;
}

.list-item-highlight{
  background: #7e00cc;
  color: white;
}

.list-item-column{
  height: inherit;
  vertical-align: center;
  display: inline-block;
  width: 33.33%;
  padding-left: 40px;
}

.ts文件

 hoverListItem() {
    this.listItemHovered = !this.listItemHovered;
  }
html css angular ng-class
2个回答
3
投票

现在你在组件上下文中创建和修改listItemHovered标志,而不是你应该为每个项目级别维护一个标志,这可以帮助轻松识别轮廓组件是否已突出显示。

[ngClass]="{'list-item-highlight': opportunity.listItemHovered}"
(mouseenter)="hoverListItem(opportunity)"
(mouseleave)="hoverListItem(opportunity)"

零件

hoverListItem(opportunity) {
   opportunity.listItemHovered = !opportunity.listItemHovered;
}

虽然我建议使用:hover伪类,如果要求只是突出显示悬停元素。通过更改CSS规则可以轻松实现这一点。这种方式可以节省几个变化检测周期。

.list-item:hover {
  background: #7e00cc;
  color: white;
}

1
投票

我建议使用directive来监听目标元素上的悬停事件并附加类:

@Directive({
    selector: '[hoverDir]'
})


 export class HoverOverDirective { 
    @HostListener('mouseenter') onMouseEnter() {
       this.elementRef.nativeElement.class = 'list-item-highlight';
    }

     @HostListener('mouseleave') onMouseLeave() {
       this.elementRef.nativeElement.class = 'list-item-not-highlight';
     }
}

或者最简单的方法是使用CSS pseudo property :hover并使用如下:

.list-item:hover {
  background: #7e00cc;
  color: white;
}  
© www.soinside.com 2019 - 2024. All rights reserved.