【发布时间】:2021-10-11 14:36:07
【问题描述】:
我有一个由六边形组成的 SVG 地图,这些六边形被分成几组。当用户将鼠标悬停在一个组上时,我希望出现一个工具提示。问题是,我希望这个工具提示有 3 秒的延迟。因此,如果用户决定在该延迟期间悬停,我想清除该延迟以阻止工具提示出现,因为他们不再悬停在它上面。工具提示消失的时间也会有延迟,以防您在快速离开前一个元素后将鼠标悬停在另一个元素上。
我为此使用了 setTimeout。我在这里所做的工作有 50% 的时间有效,但我发现如果我将鼠标悬停在上面并让工具提示显示,然后在悬停之前快速将鼠标悬停在一堆其他不同的元素上,工具提示会消失但很快再次出现。
这是我的代码,如果需要,我很乐意进一步解释。干杯!
// Setting the tooltip to appear below the tooltip wrapper
gsap.set(tip, {
yPercent: 100
});
// Tooltip Hovering Functionality with Timeouts
let hoverOutTimeout; // Timeout for hovering out
// GO through grouped elements with an event listener on mouse move, and use timeouts to delay hover
for (i = 0; i < lgas.length; i++) {
lgas[i].onmouseover = function () {
if (hoverOutTimeout) { // Check to see if the delay for the mouseleave function is running
clearTimeout(hoverOutTimeout);
//console.log("Hover back in");
} else {
//console.log("Hovering in");
}
// Set 3s delay to display tooltip
hoverTimeout = setTimeout(function () {
//console.log("Hovered in");
gsap.to(tip, {
yPercent: 0,
ease: 'bounce.out'
});
}, 3000);
}
lgas[i].onmouseleave = function () {
if (hoverTimeout) { // If delay to show tooltip is running, clear it
clearTimeout(hoverTimeout);
//console.log("Hovering back out")
hoverOutTimeout = setTimeout(() => { // Start new delay to hide tooltip
//console.log("Hovered out");
gsap.to(tip, {
yPercent: 100,
ease: 'back.in'
});
}, 2000);
}
clearTimeout(hoverTimeout);
}
}
【问题讨论】:
标签: javascript html css gsap