Angular 相对于鼠标位置的工具提示指令

Angular tooltip directive relative to mouse position

到目前为止,我已经找到了许多示例来展示如何创建一个 工具提示 ,其 位置是相对于我们添加的组件 指令。

但是,我找不到一个指令示例,该指令在将鼠标悬停在组件上时显示 相对于鼠标位置的工具提示

我怎样才能得到这个效果?


示例:

<tooltip></tooltip> <!-- default: display: none and position: absolute -->

<component-A [tooltip]="data"></component-A>
<component-B [tooltip]="data"></component-B>
<component-C [tooltip]="data"></component-C>
<!-- show tooltip on mousenter and update position on mousemove -->

我会在 3 个组件的每个 DOM 中定义工具提示,然后完全按照您现在的操作进行,减去 [tooltip] 数据绑定(除非您需要每个组件中的数据组件)。然后您可以在每个工具提示中输入您想要的任何文本,而不必担心鼠标输入和鼠标移动操作。

例如

主要成分

<component-A></component-A>
<component-B></component-B>

组件 A:

<div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip A text</span>
</div>

组件 B:

<div class="tooltip">Hover over me
      <span class="tooltiptext">Tooltip B text</span>
</div>

可扩展解决方案:


tooltipable.component.html - 这个组件是包装器,它期望子组件被分成两部分:

  • 工具提示 - 部分有条件地显示 (onMouseEnter)
  • 正文 - 正常部分(始终显示)
<app-tooltip [display]="this.display" [x]="this.x" [y]="this.y">
  <ng-content select="[tooltip]"></ng-content>
</app-tooltip>

<ng-content select="[body]"></ng-content>

tooltip.component.html - 这是要在工具提示中显示的数据的容器

<div class="tooltip"
  [style.display]="this.display ? 'block' : 'none'"
  [style.top]="y + 'px'"
  [style.left]="x + 'px'"
>
    <ng-content></ng-content>
</div>

some.component.html

<app-tooltipable>
   <div tooltip>Hello tooltip!</div>
   <div body>Hello world!</div>
</app-tooltipable>