代码之家  ›  专栏  ›  技术社区  ›  pop

mouseenter/mouseleave与@hostlistener

  •  1
  • pop  · 技术社区  · 6 年前

    在读取了所有与jquery相关的线程之后,闪烁的消息让我非常痛苦。 我还是搞不清楚。

    所以我有这个@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;
        }
      }
    

    每个 <span> 其中包含文本的闪烁。每个包含SVG的选择器都会闪烁…有什么想法吗?

    不知何故 el: ElementRef 没有被使用,尽管我出于某种原因注射了它。尝试将引用与之匹配-仍然没有运气。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Poul Kruijt    6 年前

    您的toolTipContainer正在触发 mouseleave 因为它已经超越了元素。如果你不介意你不能点击/选择任何东西。在CSS中设置 pointer-events: none 到tooltip容器。

    输入带有指令(mouseenter)的元素时,工具提示容器将覆盖此元素。现在工具提示上有光标。啊哈!这将使用指令从元素中触发(mouseleave),因此工具提示将消失。但是,不是指令又有光标了…(鼠标器)!…但是嘿!工具提示再次位于光标下…(鼠标左键)等:)

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