简而言之(TL;DR)
StackBlitz 示例
可以通过创建一个函数来计算和决定工具提示(tooltip
)的 top
和 left
属性位置。之后,可以便捷地使用 [ngStyle]
应用这些样式:
<div #container class="banner-container">
<span #element class="point-button" cdkDrag
[cdkDragBoundary]="container"
(cdkDragReleased)="updateTooltipStyle()"
></span>
<span #tooltip class="tooltip" [ngStyle]="tooltipStyle">
这是一个工具提示 :-)
</span>
</div>
在组件类中,定义该函数以计算工具提示的位置,并在视图初始化后及拖拽释放时调用它:
export class YourComponent implements AfterViewInit {
@ViewChild('container') container!: ElementRef;
@ViewChild('element') element!: ElementRef;
@ViewChild('tooltip') tooltip!: ElementRef;
tooltipStyle = {};
ngAfterViewInit() {
this.updateTooltipStyle();
}
updateTooltipStyle() {
// 计算容器、元素和工具提示的边界
const parentRect = this.container.nativeElement.getBoundingClientRect();
const elementRect = this.element.nativeElement.getBoundingClientRect();
const tooltipRect = this.tooltip.nativeElement.getBoundingClientRect();
// 计算四周的可用空间
const spaceLeft = elementRect.left - parentRect.left;
const spaceRight = parentRect.right - elementRect.right;
const spaceTop = elementRect.top - parentRect.top;
const spaceBottom = parentRect.bottom - elementRect.bottom;
// 选择水平或垂直方向上空间较大的一侧
const spaceX = Math.max(spaceLeft, spaceRight) - tooltipRect.width;
const spaceY = Math.max(spaceTop, spaceBottom) - tooltipRect.height;
let tooltipTop, tooltipLeft;
// 根据空间大小决定工具提示的对齐方式
if (spaceX > spaceY) {
tooltipLeft = spaceLeft > spaceRight
? elementRect.left - parentRect.left - tooltipRect.width - MARGIN
: elementRect.right - parentRect.left + MARGIN;
tooltipTop = Math.min(
Math.max(0, (elementRect.top - parentRect.top) + (elementRect.height - tooltipRect.height) / 2),
parentRect.height - tooltipRect.height
);
} else {
tooltipTop = spaceTop > spaceBottom
? elementRect.top - parentRect.top - tooltipRect.height - MARGIN
: elementRect.bottom - parentRect.top + MARGIN;
tooltipLeft = Math.min(
Math.max(0, (elementRect.left - parentRect.left) + (elementRect.width - tooltipRect.width) / 2),
parentRect.width - tooltipRect.width
);
}
// 应用计算好的样式
this.tooltipStyle = {
left: `${tooltipLeft}px`,
top: `${tooltipTop}px`,
width: `${tooltipRect.width}px`
};
}
}
注意:代码中的 MARGIN
是一个未定义的常量,你需要根据实际情况定义它,作为工具提示与元素之间的间距。这里提供了一个工作中的 StackBlitz 示例,尽管给出的链接似乎遇到了错误,但上述代码段概括了实现这一功能的方法。