Angular 2 悬停事件

当你将鼠标悬停在屏幕上的某些元素上时,你无需单击即可访问信息。你甚至可以在鼠标悬停的元素上执行一些功能。

本文着眼于在元素上执行悬停事件功能鼠标悬停的简单解决方案。

我们将应用 mouseentermouseleave 函数来创建悬停事件。第二种方法也将使用两个函数,即 mouseovermouseout

然后,我们将应用更高级的方法来执行悬停事件。

Angular 中的 mouseentermouseleave 应用程序

在处理成对出现的函数时,我们需要为每个函数传递条目。

我们使用 mouseenter 函数来声明当我们将鼠标悬停在元素上时会发生什么。mouseleave 函数然后确定将鼠标移开时会发生什么。

HTML 输入将如下所示:

<div style="text-align: center;">
  <h2>Mouse Hover Event</h2>
</div>
<button
  class="btn-primary btn"
  (mouseenter)="showImage = true"
  (mouseleave)="showImage = false"
>
  Hover Over Me!
</button>
<br />
<img
  *ngIf="showImage"
  src="https://www.zadmei.com/wp-content/uploads/2023/03/560.jpg"
/>

之后,我们将编写 app.component.ts,如下所示:

import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
title = 'mouse-hover';
showImage: boolean;
constructor() {
this.showImage = false;
}
}

Angular 中的 mouseovermouseout 应用程序

mouseovermouseout 属性像前面解释的方法一样成对工作,我们只需要切换功能,瞧:

<div style="text-align: center;">
  <h2>Mouse Hover Event</h2>
</div>
<button
  class="btn-primary btn"
  (mouseover)="showImage = true"
  (mouseout)="showImage = false"
>
  Hover Over Me!
</button>
<br />
<img
  *ngIf="showImage"
  src="https://www.zadmei.com/wp-content/uploads/2023/03/560.jpg"
/>

mouseentermouseleave 作为 Angular 中的函数传递

我们将通过以下方法获得更多创意和复杂性,我们将在其中将 mouseentermouseleave 事件作为函数传递。

HTML 将稍作调整:

<div style="text-align: center;">
  <h2>Mouse Hover Event</h2>
</div>
<button
  class="btn-primary btn"
  (mouseover)="showImg(true)"
  (mouseleave)="showImg(false)"
>
  Hover Over Me!
</button>
<br />
<img
  *ngIf="showImage"
  src="https://www.zadmei.com/wp-content/uploads/2023/03/560.jpg"
/>

还有 app.component.ts

import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
title = 'mouse-hover';
showImage: boolean;
constructor() {
this.showImage = false;
}
showImg(hover: boolean) {
this.showImage = hover;
}
}