tooltip 现在功能完整,但其显示效果不太容易注意到。你可以通过为显示和隐藏状态添加一些动画来解决这个问题。有很多方式可以为元素添加动画,但在本例中,使用 CSS 过渡就足够了。

为"正在显示"等元素状态设置样式的简单方法是添加一个与状态对应的属性。为此,添加一个 reflect 到属性的 showing 属性:

@property({reflect: true, type: Boolean})
showing = false;
static properties = {
offset: {type: Number},
showing: {reflect: true, type: Boolean},
};
constructor() {
super();
this.offset = 4;
this.showing = false;
}

现在为过渡动画添加 CSS。设置元素在显示时的 opacityscale。这将在指定的持续时间内进行过渡。你可以自由尝试其他可以过渡的属性。

:host {
/* ... */
opacity: 0;
transform: scale(0.75);
transition: opacity, transform;
transition-duration: 0.33s;
}

:host([showing]) {
opacity: 1;
transform: scale(1);
}

现在,在 show 方法中设置 showing

show = () => {
// ...
this.showing = true;
};

hide 方法中,移除将 display 设置为 none 的代码,因为这现在将在过渡结束时完成。只需在这里将 showing 设置为 false 以触发过渡。然后添加一个 finishHide 方法,在过渡完成且 showingfalse 时将 display 设置为 none

hide = () => {
this.showing = false;
};

finishHide = () => {
if (!this.showing) {
this.style.display = 'none';
}
};

浏览器在过渡完成时会发送 transitionEnd 事件。将其连接以完成 tooltip 的隐藏。这是一次性的工作,你可以在元素 constructor 中完成。在类定义的顶部附近添加:

constructor() {
super();
// 动画结束时完成隐藏
this.addEventListener('transitionend', this.finishHide);
}
constructor() {
super();
// 动画结束时完成隐藏
this.addEventListener('transitionend', this.finishHide);
this.offset = 4;
this.showing = false;
}

现在将指针移到 tooltip 目标上。你应该能看到 tooltip 在显示和隐藏时有过渡效果。