角度工具提示离开视口

时间:2019-04-05 09:57:12

标签: javascript angular tooltip

我有一个动态生成的工具提示,其中使用@Input将宽度和内容提供给组件。但是,我无法找到一种方法来设置工具提示的位置,以使其停留在视口内而不位于内容上方。只要可悬浮内容位于视口的边缘(如上/下/左/右),工具提示就不会显示在视口内。

我知道我必须使用getBoundingClientRect()计算悬停元素的位置,但是如何以工具提示不与悬停内容重叠的方式设置位置。

这是我的代码:

app.component.html

<div style="background:red;">
<p>orem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsu
  and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsu
  PageMaker including versions of Lorem Ipsu
  and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsu
</p>

<button awesomeTooltip="Hello World!"  image="https://placeimg.com/640/480/any">Hi there, check for a tooltip</button>
</div>

tooltip.component.html

   <img [src]="image" width= "300px" @tooltip>

tooltip.directive.ts

import { ComponentRef, Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core';
import { Overlay, OverlayPositionBuilder, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';

import { AwesomeTooltipComponent } from './tooltip.component';

@Directive({ selector: '[awesomeTooltip]' })
export class AwesomeTooltipDirective implements OnInit {

  @Input('awesomeTooltip') text = '';
  @Input('image') image = '';
  private overlayRef: OverlayRef;

  constructor(private overlay: Overlay,
              private overlayPositionBuilder: OverlayPositionBuilder,
              private elementRef: ElementRef) {
  }

  ngOnInit(): void {
    const positionStrategy = this.overlayPositionBuilder
      .flexibleConnectedTo(this.elementRef)
      .withPositions([{
        originX: 'center',
        originY: 'top',
        overlayX: 'center',
        overlayY: 'bottom',
        offsetY: -8,
      }]);

    this.overlayRef = this.overlay.create({ positionStrategy });
  }

  @HostListener('mouseenter')
  show() {
    const tooltipRef: ComponentRef<AwesomeTooltipComponent>
      = this.overlayRef.attach(new ComponentPortal(AwesomeTooltipComponent));
    tooltipRef.instance.text = this.text;
    tooltipRef.instance.image = this.image;
  }

  @HostListener('mouseout')
  hide() {
    this.overlayRef.detach();
  }
}

Stackblitz链接为here

我正在寻找的结果是,每当工具提示出来时,工具提示都应该在视口内。

0 个答案:

没有答案