【问题标题】:Revealing items on hover, hide them after X seconds悬停时显示项目,X 秒后隐藏它们
【发布时间】:2020-12-22 11:46:57
【问题描述】:

我正在尝试实现“显示”效果,当我将项目悬停在网格中时会显示它们。 这里一切正常,但一旦显示出来,我想让它们在 X 秒后再次消失——所以并不是当你将鼠标从项目上移开时它们会立即消失。

这是我迄今为止尝试过的,但是在我将鼠标从项目上移开后,这些项目并没有回到它们的“未显示”状态。

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

有人知道如何解决吗? 提前致谢。

【问题讨论】:

    标签: javascript jquery css timeout


    【解决方案1】:

    问题在于 this 在 setTimeout 中具有不同的含义 - 您可以存储 box (this) 并重复使用它。

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

    【讨论】:

    • 这就是必要的,事实证明..我理解作者的问题有点不正确,并且做了不同的事情。不错的解决方案!
    • 一开始我给你加分,不知道是谁给减分的。
    • 谢谢,无论内容如何,​​我的大多数答案似乎都得到 立即 -1,认为有人为我提供了答案,但看不到是谁想想“哦,那只是 x,不用担心”
    • 最近同样的情况触动了我:(
    【解决方案2】:

    您应该使用mouseentermouseleave 事件并在每个事件中添加单独的功能。 传递给 setTimeout 的回调函数中可能会丢失对 this 的引用。

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

    【讨论】:

    • .hover() 只是mouseenter/mouseleave 的简写,因此无需更改为这些api.jquery.com/hover
    • 同意。但是你应该使你的代码尽可能的可读和明确。因此,我个人会选择单独的函数定义。
    • 完美运行!我需要删除 clearTimeout(timeout);虽然为了达到想要的效果。谢谢!
    • 基本上,clearTimeout 将确保如果鼠标再次回到元素上,调用堆栈中来自mouseleave 的先前淡入操作不会执行。
    • @mappie 你是对的!刚刚做到了 :) 再次感谢!
    【解决方案3】:

    有必要吗?我使用了事件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>

    【讨论】:

      猜你喜欢
      • 2014-03-18
      • 1970-01-01
      • 2011-07-21
      • 2012-06-22
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多