Angular 2 ホバーイベント
-
Angular の
mouseenterおよびmouseleaveの応用 -
Angular の
mouseoverおよびmouseoutアプリケーション -
Angular の関数として
mouseenterとmouseleaveを渡す
画面上の特定の要素にマウスを合わせると、クリックしなくても情報にアクセスできます。マウスにカーソルを合わせると、要素に対していくつかの機能を実行することもできます。
この記事では、要素に対してホバーイベント関数のマウスホバーを実行するための簡単なソリューションについて説明します。
mouseenter および mouseleave 関数を適用して、ホバーイベントを作成します。2 番目の方法でも、mouseover と mouseout という 2つの関数を使います。
次に、より高度なアプローチを適用してホバーイベントを実行します。
Angular の mouseenter および mouseleave の応用
ペアで提供される関数を処理する場合、各関数のエントリを渡す必要があります。
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://vangogh.teespring.com/v3/image/so-OI-9L5KAWsqHQuv6gQwymSQ8/480/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 の mouseover および mouseout アプリケーション
mouseover 属性と mouseout 属性は、前に説明した方法のようにペアで機能します。関数と出来上がりを切り替えるだけで済みます。
<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://vangogh.teespring.com/v3/image/so-OI-9L5KAWsqHQuv6gQwymSQ8/480/560.jpg"
/>
Angular の関数として mouseenter と mouseleave を渡す
次のメソッドを使用すると、もう少しクリエイティブで洗練されたものになります。このメソッドでは、mouseenter イベントと mouseleave イベントを関数として渡します。
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://vangogh.teespring.com/v3/image/so-OI-9L5KAWsqHQuv6gQwymSQ8/480/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;
}
}
Fisayo is a tech expert and enthusiast who loves to solve problems, seek new challenges and aim to spread the knowledge of what she has learned across the globe.
LinkedIn