简体   繁体   中英

Angular tooltip directive relative to mouse position

So far I have found many examples showing how to create a tooltip whose position is relative to the component to which we added the directive.

However, I can't find an example of a directive that, when hovering over a component, displays a tooltip relative to the mouse position .

How can i get this effect?


Example:

<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 -->

I would define the tooltip in each of the 3 component's DOM's, then do exactly what your doing right now, minus the [tooltip] data binding (unless you need the data in each of your components). You can then enter whatever text you want in each tooltip without having to worry about the mouse enter and mouse move actions.

For example

Main Component

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

Component A:

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

Component B:

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

Scalable solution:


tooltipable.component.html - this component is wrapper which expects the child to be divided into two sections:

  • tooltip - section conditionally displayed (onMouseEnter)
  • body - normal section (always displayed)
<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 - this is a container for data to be displayed in the tooltip

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM