工具提示定位
智能定位工具提示,防止超出视口边界
实现原理
使用 getBoundingClientRect() 获取目标元素和视口的位置信息,
动态计算工具提示的最佳位置,避免超出视口。
function positionTooltip(element, tooltip) {
const rect = element.getBoundingClientRect();
const tooltipRect = tooltip.getBoundingClientRect();
// 默认显示在上方
let top = rect.top - tooltipRect.height - 10;
let left = rect.left + (rect.width - tooltipRect.width) / 2;
// 检查是否超出顶部
if (top < 0) {
// 改为显示在下方
top = rect.bottom + 10;
}
// 检查是否超出左右边界
if (left < 0) {
left = 10;
} else if (left + tooltipRect.width > window.innerWidth) {
left = window.innerWidth - tooltipRect.width - 10;
}
tooltip.style.top = top + 'px';
tooltip.style.left = left + 'px';
}
示例:智能工具提示
悬停在按钮上查看工具提示(会自动避开边界)
提示框位置
位置策略:
-
Top:
0px
Left:
0px
💡 关键点
工具提示会自动选择最佳位置:
1. 优先显示在上方
2. 如果上方空间不足,显示在下方
3. 防止超出左右边界
总结
- 使用 getBoundingClientRect() 获取元素位置
- 计算工具提示的默认位置
- 检测是否会超出视口边界
- 动态调整位置到合适的方向
- 确保工具提示始终可见