我目前正在尝试显示名称列表及其分配的图像。
因此我创建了一个包含所有名称及其图像的服务(忽略链接):
import { Case } from './case';
export const CASES: Case[] = [
{ name: 'Diesel', image: '/assets/images/diesel.png', link: '' },
{ name: 'WeWork Berlin', image: '/assets/images/berlin.png', link: '' },
{ name: 'Fritzhansen', image: '/assets/images/fritzhansen.png', link: '' },
{ name: 'Savum', image: '/assets/images/savum.png', link: '' },
{ name: 'Eskay', image: '/assets/images/eskay.png', link: '' },
{ name: 'Diesel', image: '/assets/images/diesel-snd.png', link: '' },
{ name: 'Mobilia', image: '/assets/images/mobilia.png', link: '' },
{ name: 'Rarekind', image: '/assets/images/rarekind.png', link: '' }
];
这个案例列表是在案例列表 component.ts 中获取的:
import {Component, OnInit} from '@angular/core';
import { CASES } from '../mock/mock-cases';
@Component({
selector: 'app-case-list',
templateUrl: './case-list.component.html',
styleUrls: ['./case-list.component.scss']
})
export class CaseListComponent implements OnInit {
cases = CASES;
...
}
在案例列表的 html 文件中,我遍历此数组以显示名称及其图像:
<div *ngFor="let case of cases" class="container-fluid d-flex justify-content-center">
<ul>
<li class="text-center">
{{ case.name }}
</li>
</ul>
<img src="{{ case.image }}" alt="First" class="position-absolute align-self-center d-none">
</div>
它有效,但我希望它的功能有所不同。当前正在显示所有图像。
但我希望图像仅在悬停关联的 li
项时可见。此外,仅分配给 li
的图像> 元素(悬停)应显示 - f.e.如果 li
Savum 悬停,则只显示其图像 savum.png
。
我如何在 Angular 中实现这种行为?
最佳答案
Make two functions for mouseenter and mouseleave, so that we can set the image url when you hover the particular list item. mouseenter function used to get the url of the particular item by passing as a parameter and stored it into a public property imageUrl.
你的 .ts 文件应该是这样的。
export class CaseListComponent implements OnInit {
cases = CASES;
imageUrl: string;
mouseEnter(url: string) {
this.imageUrl = url;
}
mouseLeave() {
this.imageUrl = null;
}
}
// And then use that value to update the src attribute of the image tag and make a note only it contains a string it will be displayed and i am not going to do the validation because its not important in this case.
.html 会像这样
<div class="container-fluid d-flex justify-content-center">
<ul>
<li (mouseenter)="mouseEnter(case.image)" (mouseleave)="mouseLeave()" class="text-center" *ngFor="let case of cases">
{{ case.name }}
</li>
</ul>
<img *ngIf="!!imageUrl" [src]="imageUrl" class="position-absolute align-self-center">
</div>
关于html - 遍历元素列表,在悬停时显示分配的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56634276/