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

时间:2019-07-25 09:18:30

标签: angular

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

我无法获得适当功能的问题,我尝试了几种解决方案,但都无济于事。我准备了这张堆叠闪电战,可以更好地解释https://stackblitz.com/edit/angular-8krjit

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

2 个答案:

答案 0 :(得分:2)

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

尝试一下:

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>

  

以下是 Working Sample StackBlitz 供您参考。

答案 1 :(得分:0)

使用mousemove事件而不是mouseover事件解决方案,这里是working stackblitz

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
  );
}
相关问题