悬停时显示项目,X秒后隐藏它们

问题描述

我试图实现一种“显示效果,当我将它们悬停在网格上时,它们会显示它们。 一切正常,但一旦显示,我想让它们在X秒后再次消失–因此,当您将鼠标从该项目移开时,它们并不会立即消失。

这是我到目前为止尝试过的方法,但是当我将鼠标从项目上移开后,这些项目不会恢复到它们的“未公开”状态。

var timeout;
  $(".home-Box").hover(function () {
      clearTimeout(timeout);
      $(this).css("opacity",1);
  },function () {
      timeout = setTimeout(function(){
        $(this).css("opacity",0);
      },500);
  });

有人知道如何解决吗? 预先感谢。

解决方法

有必要吗?我使用事件mouseover而不是hover,因为hover总是会在鼠标移动时触发,即使您尝试将光标移离对象也是如此。

$(".home-box").mouseover(function () {
      $('img').css("opacity",1);
      setTimeout(function(){
        $('img').css("opacity",0);
  },2000);
});
  
.home-box {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 300px;
  height: 300px;
  border: 1px solid green;
  position: relative;
}

img {
  opacity: 0;
  position: absolute;
  height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="home-box">
  hover me pls and wait...
  <img src="https://im0-tub-ru.yandex.net/i?id=1a59e5c138260403e2230f0d2b264513&n=13">
</div>

,

您应该使用app.post(‘/register’,passport.authenticate(‘local’),(req,res) => { // } mouseenter事件,并在每个事件中添加单独的功能。 在传递给setTimeout的回调函数中,对mouseleave的引用可能会丢失。

this
,

问题在于this在setTimeout中的含义不同-您可以存储boxthis)并重新使用。

var timeout;
$(".home-box").hover(function() {
  clearTimeout(timeout);
  $(this).css("opacity",1);
},function() {
  var box = this;
  timeout = setTimeout(function() {
    $(box).css("opacity",500);
});