javascript - SetTimeout 在 jQuery 中不能正常工作

标签 javascript jquery html

This is my code . 如果我将鼠标放在每个图像上,我希望图像在一秒钟后变大,但是 setTimeout 没有响应。即使我将 alert() 函数放在 menuChanging() 函数的开头,它也会运行但我的其余代码不会执行(它会立即运行,而不是一秒钟后)。

最佳答案

您将在鼠标悬停时立即调用函数 menuChanging,而您需要将函数引用传递给 setTimeout

$(function() {
  $(".hormenu > div").hover(function() {
    $(this).data('hoverTimer', setTimeout(menuChanging.bind(this), 1000));
  }, function() {
    var $this = $(this);
    //if you move out before 1s then clear the timer
    clearTimeout($this.data('hoverTimer'));

    //when the mouse is moved out restore to initial state if required
    if ($this.hasClass('current')) {
      $this.toggleClass("current other").animate({
        width: "100px",
        opacity: "0.5"
      }, 750, 'easeOutBounce');
    }
  });
});

function menuChanging() {
  var duration = 750;
  $(".hormenu > .current").not(this).toggleClass("current other").animate({
    width: "100px",
    opacity: "0.5"
  }, duration, 'easeOutBounce');
  $(this).removeClass("other").addClass("current").animate({
    width: "600px",
    opacity: "1"
  }, duration, 'easeOutBounce');
}
.hormenu {
  height: 500px;
  width: 1800px;
}
img {
  height: 100%;
  width: 100%;
}
.hormenu div {
  width: 100px;
  overflow: hidden;
  display: block;
  float: left;
  height: 100%;
}
.other {
  opacity: 0.5;
}
img {
  width: 600px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<div class="hormenu">
  <div class="current">
    <img src="http://img0.mxstatic.com/wallpapers/b844e6ef0e3320bc945a9b5b1cd196f9_large.jpeg" alt="" />
  </div>
  <div class="other">
    <img src="http://img0.mxstatic.com/wallpapers/20c41d877dfbed0e52947f51846df781_large.jpeg" alt="" />
  </div>
  <div class="other">
    <img src="http://img0.mxstatic.com/wallpapers/b844e6ef0e3320bc945a9b5b1cd196f9_large.jpeg" alt="" />
  </div>
</div>

关于javascript - SetTimeout 在 jQuery 中不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31872976/

相关文章:

javascript - 无法使用 javascript 将标签内部的值递增 1

javascript - 如何通过 ajax 通过 $POST 发送对象数据(从 jQuery 到 vanilla JS)

html - 在格式化 HTML 文档时,我无法让 <cite> 文本正确对齐

java - 正则表达式从字符串中删除不带 <br/> 制表符的 HTML 标签

JavaScript : format string and avoid multiple replace

javascript - 保存javascript生成的文档

javascript从弹出窗口返回值作为没有输入字段的函数中的变量

php - 如何制作 Accordion 菜单并在cookie中保存位置(包含代码)

显示 GIF 的 JavaScript 函数

javascript - Node.js fs ENOENT 错误