悬停几秒钟后启动功能

Start function after hover a couple second

本文关键字:启动 功能 几秒 悬停      更新时间:2024-06-28

我想在div悬停1500毫秒后fadeIn()。我需要如何检查用户是否悬停在1500毫秒上

<div id=bla>Hover this</div>
var bla = $('#bla');
bla.hover(function(){       
        bla.hide().html("HEHE").fadeIn("slow");
});

可以使用setTimeout,如果用户像这样离开bla,只需清除setTimeout

var timeout,
bla = $('#bla');
bla.hover(
  function () {
    timeout = setTimeout( function() {       
      bla.hide().html("HEHE").fadeIn("slow")
    }, 1500);
  }, 
  function () {
    clearTimeout(timeout);
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bla">Text</div>

您可以使用与setTimeout和hoverOut相结合的自定义标志(http://api.jquery.com/hover/)

(function() {                                   // Scope protected
  var bla = $('#bla');                          // Your div
  var timeout;                                  // Variable to store the setTimeout id
  bla.hover(function() {                        // Hover can take two callbacks
    timeout = setTimeout(function() {           // On hover, we setTimeout and store it
      bla.hide().html("HEHE").fadeIn("slow");   // 1500ms later, we fadeIn
    }, 1500);
  }, function () {                              // Unhover callback
    clearTimeout(timeout);                      // We simply clear the timeout
  });
})();                                           // Directly calling the scope

我们在悬停时设置了一个超时回调,但在取消悬停时将其清除。