检测子鼠标何时被父鼠标事件悬停



我有一个pointer-events: none的子元素,我想在使用父元素鼠标事件悬停子元素时重新启用pointer-events

我无法获得正确功能的问题,我尝试了几种解决方案,但没有一种奏效。我准备了这个堆栈闪电战,它更好地解释了它 https://stackblitz.com/edit/angular-8krjit

更新只是为了澄清,当指针进入容器时,不应启用子项的指针事件,而应在指针进入子项时启用

您可以使用@ViewChild手动设置nativeElement上的style.pointerEventsstyle.cursor属性

试一试:

import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
@ViewChild('box', { static: false }) box: ElementRef;
hovered: boolean = false;
onMouseOver(e) {
console.log(e);
this.hovered = true;
(<HTMLDivElement>this.box.nativeElement).style.pointerEvents = 'auto';
(<HTMLDivElement>this.box.nativeElement).style.cursor = 'pointer';
}
onMouseOut(e) {
this.hovered = false;
(<HTMLDivElement>this.box.nativeElement).style.pointerEvents = 'none';
(<HTMLDivElement>this.box.nativeElement).style.cursor = 'none';
}
onClick() {
console.log('Box Clicked');
}
}

在模板中:

<div 
class="container" 
(mouseover)="onMouseOver($event)" 
(mouseout)="onMouseOut($event)">
<div 
#box 
class="box"
[class.hovered]="hovered" 
(click)="onClick()">
</div>
</div>
<h3>mouseover the box: {{hovered}}</h3>

这是您的参考的工作示例堆栈闪电战

使用mousemove事件而不是mouseover得到了解决方案,这是一个有效的堆栈闪电战

import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div class="container" (mousemove)="onMouseMove($event, box)">
<div #box class="box" [class.hovered]="hovered"></div>
</div>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
hovered = false;
onMouseMove(e, box) {
const rect = box.getBoundingClientRect();
this.hovered = isWithinBounds(e, rect);
}
}
function isWithinBounds(e: any, rect: ClientRect): boolean {
return (
e.clientX >= rect.left &&
e.clientX <= rect.left + rect.width &&
e.clientY >= rect.top &&
e.clientY <= rect.top + rect.height
);
}

最新更新