没有 jQuery 的带有延迟鼠标移出的 js 工具提示

js Tooltip with delayed mouseout without jQuery

我想在悬停 div 时显示 工具提示 。当鼠标悬停在 tooltip-div.

时也应该显示

添加一个事件侦听器可以完成这项工作,但如果两个 div 没有重叠,则 mouseout 会在鼠标位于它们之间且工具提示消失时调用。

现在我想为 mouseout 添加延迟,当它获得新的鼠标悬停时被取消,但我不知道如何。

document.getElementById("hoverElem").addEventListener("mouseover", function() {
  document.getElementById("displayElem").style.visibility = "visible";
});

document.getElementById("hoverElem").addEventListener("mouseout", function() {
  document.getElementById("displayElem").style.visibility = "hidden";
});
#hoverElem {
  position: fixed;
  height: 100px;
  weidth: 200px;
  top: 0px;
  left: 50%;
  background-color: white;
}
#displayElem {
  position: fixed;
  height: 100px;
  weidth: 20px;
  top: 150px;
  left: 50%;
  background-color: yellow;
  visibility: hidden;
}
<div id="hoverElem">
  A little Div
  <div id="displayElem">
    Tooltip to show
  </div>
</div>

您可以在 mouseleave 中启动一个计时器,然后在 mouseenter 中清除它 displayElem 喜欢

document.getElementById("hoverElem").addEventListener("mouseenter", function() {
  document.getElementById("displayElem").style.visibility = "visible";
});

var hoverTimer;
document.getElementById("hoverElem").addEventListener("mouseleave", function() {
  hoverTimer = setTimeout(function() {
    document.getElementById("displayElem").style.visibility = "hidden";
  }, 500);
});
document.getElementById("displayElem").addEventListener("mouseenter", function() {
  clearTimeout(hoverTimer);
});

document.getElementById("displayElem").addEventListener("mouseleave", function() {
  this.style.visibility = "hidden";
});
#hoverElem {
  position: fixed;
  height: 100px;
  weidth: 200px;
  top: 0px;
  left: 50%;
  background-color: white;
}
#displayElem {
  position: fixed;
  height: 100px;
  weidth: 20px;
  top: 150px;
  left: 50%;
  background-color: yellow;
  visibility: hidden;
}
<div id="hoverElem">
  A little Div
  <div id="displayElem">
    Tooltip to show
  </div>
</div>

您是否考虑过使用纯 CSS 来代替?

div {
  position: fixed;
  height: 100px;
  width: 200px;
  top: 0px;
  left: 50%;
  background-color: black;
}

div:hover span,
span:hover{
  opacity:1;
}

span {
  display:block;
  opacity:0;
  color:orange;
  -webkit-transition-delay: .5s;
  transition-delay: .5s;
  -webkit-transition:opacity 1s ;
  transition:opacity 1s ;
    
  
  position: fixed;
  height: 100px;
  width: 100px;
  top: 150px;
  left: 50%;
  background-color: yellow;
  visibility: visible;
}
<div>
  <span>lorem Ipsum</span>
</div>