常见需求:鼠标划上2s后显示标签全部内容
我是通过mouseover事件,获取鼠标在视口的位置,创建元素并将蓝色元素的innerText给新创建的元素,并将鼠标视口位置信息x、y赋值给新元素的left、top实现的。 但是会出现鼠标疯狂闪烁,新元素不出现的问题,开始我以为是定时器的问题,后来研究表明,是因为新创建的元素与鼠标在视口的位置相同,mouseover事件无法判断鼠标是落在蓝色元素,还是新创建的元素所致,于是,将新元素的left、top值在x、y的基础上加10px,问题得以解决。 代码如下:
showWholeTitle(e) {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
if (e.target.className == "el-timeline-item__content") {
let app = document.getElementById("app"),
text = e.target.innerText,
container = document.createElement("div"),
x = e.clientX,
y = e.clientY;
container.innerText = text;
container.className = "show-whole-title";
container.style.left = x + 10 + "px";
container.style.top = y + 10 + "px";
this.timer = setTimeout(() => {
app.appendChild(container);
}, 1000);
}
},
removeWholeTitle() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
let app = document.getElementById("app");
let container = document.getElementsByClassName("show-whole-title")[0];
if (!container) return;
app.removeChild(container);
}