无法在 JavaScript 中相应地计算出“setTimeout”函数

问题描述 投票:0回答:0

代码:

function mouseSlideIn() {
  document.getElementById("box").style =
    "background: blue; height: 50px; width: 50px;";
}

function mouseSlideOut() {
  setTimeout(function() {
    document.getElementById("box").style = "";
    document.getElementById("eventDiv").style = "";
  }, 2000);
}
body {
  background: grey;
  margin: 0;
}

#eventDiv {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 90vh;
  background: powderblue;
  border-radius: 20px;
  transition: 0.8s;
  transition-timing-function: ease;
}

#box {
  position: relative;
  background: red;
  height: 150px;
  width: 150px;
  transition: 0.5s;
  transition-timing-function: ease;
}
<br>
<center>
  <div id="eventDiv" onmouseover="mouseSlideIn()" onmouseout="mouseSlideOut()">
    <div id="box"></div>
    <!--Above is the red box i.e. inside the main DIV-->
  </div>
</center>

目标:

  1. 当我将鼠标悬停在
    id="eventDIV"
    (最外层的div)上时,
    id="box"
    必须缩小并改变颜色。
  2. 当我将 out 悬停在
    id="eventDIV"
    上时,
    id="box"
    必须恢复到原来的大小和颜色。
  3. 但是,在盒子恢复到原来的状态之前,我想要延迟(比方说
    2000ms
    )。
  4. 这可以在
    setTimeout
    功能的帮助下实现。

问题:

  1. 当我在 id="eventDIV" 用完之前将
    out
    悬停在
    setTimeout
    上,即
    2000ms
    ,它会破坏代码。
  2. 当我再次将 over 悬停时,它无法正常运行(即):即使光标位于
    id="eventDIV"
    内,也会执行
    mouseSlideOut()
    函数,该函数应该在
    onmouseout
    事件上调用;那是我悬停out.
  3. 的时候
  4. 一直重复同样的错误,直到我刷新代码。

我尝试了什么:

  1. 我试过使用
    clearTimeout
    功能,但它似乎没有帮助。
  2. 其他一些无效的方法。

注:

  • 我是JS的新手
  • 我不希望 CSS/伪元素有任何变化(
    :hover
    )。
  • 我想通过JS试试(如果可能的话)
  • 这只是练习代码,我将在其他地方实现它(如果有效的话)。
  • 提前致谢。
javascript mouseevent settimeout mouseover mouseout
© www.soinside.com 2019 - 2024. All rights reserved.