tooltip 应该显示在目标元素附近。为了允许对此进行一些控制,首先在类定义内部创建一个 offset 属性:
// 位置偏移property({type: Number})offset = 4; static properties = { offset: {type: Number},};
constructor() { super(); // 位置偏移 this.offset = 4;} 由于目标元素的位置可能会改变,因此每次显示 tooltip 时都需要重新定位。同样,为了简单且稳健地实现这一点,使用内联样式。
show = () => { this.style.cssText = ''; // 在目标附近定位 tooltip。 const {x, y, height} = this.target!.getBoundingClientRect(); this.style.left = `${x}px`; this.style.top = `${y + height + this.offset}px`;}; show = () => { this.style.cssText = ''; // 在目标附近定位 tooltip。 const {x, y, height} = this.target.getBoundingClientRect(); this.style.left = `${x}px`; this.style.top = `${y + height + this.offset}px`;}; getBoundingClientRect API 提供目标元素的布局度量信息。
对其返回值使用了对象解构语法。
添加代码后,尝试触发 tooltip。input 和问候语的 tooltip 应该对齐得更好,显示在目标元素下方。但是,方框 3 的 tooltip 大小不正确,并且根据你的屏幕大小,方框的 tooltip 可能会超出预览窗口的底部。接下来你将修复这个问题。