jav*_*235 4 html css ng-class angular
我正在尝试使用 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 布尔值触发 css 类“list-item-highlight”然后将背景更改为不同颜色的值。
我面临的问题是,将鼠标指针悬停在“列表项”div 上时,我的所有“列表项”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>
Run Code Online (Sandbox Code Playgroud)
.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;
}
Run Code Online (Sandbox Code Playgroud)
.ts 文件
hoverListItem() {
this.listItemHovered = !this.listItemHovered;
}
Run Code Online (Sandbox Code Playgroud)
现在,您正在listItemHovered组件上下文中创建和修改标志,而不是您应该为每个项目级别维护一个标志,这可以帮助轻松识别组件是否已突出显示。
[ngClass]="{'list-item-highlight': opportunity.listItemHovered}"
(mouseenter)="hoverListItem(opportunity)"
(mouseleave)="hoverListItem(opportunity)"
Run Code Online (Sandbox Code Playgroud)
成分
hoverListItem(opportunity) {
opportunity.listItemHovered = !opportunity.listItemHovered;
}
Run Code Online (Sandbox Code Playgroud)
:hover不过,如果需要只是突出显示悬停时的元素,我建议使用伪类。通过更改 CSS 规则可以轻松实现这一点。这种方式可以节省几个要运行的变更检测周期。
.list-item:hover {
background: #7e00cc;
color: white;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11989 次 |
| 最近记录: |