mouseenter / mouseleave 与 @HostListener

pop*_*pop 5 mouseevent typescript angular2-directives angular2-hostbinding angular

闪烁快要了我的命,在阅读了所有 jQuery 相关线程mdn 后,我仍然无法弄清楚。

所以我有这个 @Directive 用于显示工具提示,这就是我将其绑定到元素的方式:

  @HostListener('mouseenter', ['$event']) onEnter( e: MouseEvent ) {
    this.showTooltip(e);
  }

  @HostListener('mouseleave', ['$event']) onLeave( e: MouseEvent ) {
    this.hideTooltip(e);
  }

  @HostListener('click', ['$event']) onClick( e: MouseEvent ) {
    this.hideTooltip(e);
  }

  constructor(
    private el: ElementRef,
    private renderer: Renderer2,
    private coordsService: CoordsService,
    @Inject(DOCUMENT) doc
  ) {
    this.docBody = doc.body;
  }

  public ngAfterViewInit(): void {
    this.tooltipContainer = this.renderer.createElement('div');
    this.renderer.addClass( this.tooltipContainer, 'tooltip--tip');
    this.renderer.addClass( this.tooltipContainer, 'tooltip--pos_' + this.position);
  }

  public showTooltip( e: MouseEvent ): void {

    if ( this.tooltip !== null ) {

      // text 
      this.selectedTooltip = this.renderer.createText( this.tooltip );

      // append to body
      this.renderer.appendChild( this.tooltipContainer, this.selectedTooltip);
      this.renderer.appendChild( this.docBody, this.tooltipContainer );

      // target element
      const target: HTMLElement = <HTMLElement>e.target;
      const bbox: ClientRect = target.getBoundingClientRect();

      // the array holds the pixel position of the property; should sync with top:left
      let coords: ElementCoords = this.coordsService.setPositionCoords(bbox, this.position, this.tooltipContainer, { left: -6 } );

      // write position
      this.renderer.setStyle( this.tooltipContainer, 'top', coords.top+'px' );
      this.renderer.setStyle( this.tooltipContainer, 'left', coords.left+'px' );
    }

  }

  public hideTooltip( e: MouseEvent ): void {
    if ( this.selectedTooltip ) {
      this.renderer.removeChild ( this.tooltipContainer, this.selectedTooltip);
      this.renderer.removeChild( this.docBody, this.tooltipContainer );
      this.selectedTooltip = null;
    }
  }
Run Code Online (Sandbox Code Playgroud)

每一个<span>有文字的东西都会闪烁。每个包含 SVG 的选择器都会闪烁...有什么想法吗?

附言。尽管我出于某种原因注入了它,但不知何故el: ElementRef没有被使用。尝试匹配对其的引用 - 仍然没有运气。

Pie*_*Duc 2

您的 tooltipContainer 正在触发 amouseleave因为它位于元素上方。如果您不介意的话,您无法单击/选择那里的任何内容。在你的 css 中设置pointer-events: none为 tooltipContainer。

您使用指令(mouseenter)输入元素,工具提示容器将覆盖该元素。现在工具提示已将光标置于其上。啊哈!这会使用指令触发元素的 (mouseleave),因此工具提示消失。但是,嘿,不是指令再次有光标...(鼠标输入)!...但是嘿!工具提示再次位于光标下方...(鼠标离开)...等等:)

使用指针事件,您可以确保覆盖元素不会接收任何事件,并且这些事件会被触发到其下方的元素。不过,您也可以尝试使工具提示不与元素重叠,但这取决于您