SetTimeout在jQuery中不能正常工作

SetTimeout does not work correctly in jQuery

本文关键字:工作 常工作 jQuery 不能 SetTimeout      更新时间:2023-09-26

这是我的代码。我想让图像在一秒钟后变大,如果我把鼠标放在每个图像上,但是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>

你可以在这里找到解决问题的方法。

$(function(){
    $(".hormenu div").mouseover(
        function()
        {
            setTimeout(menuChanging($(this)),1000);
        }
        );
});
function menuChanging(div) {
    return function(){
        var duration = 750 ;
        if (!div.hasClass("current")) {
            $(".current").removeClass("current").addClass("other").animate({
                width: "100px",
                opacity: "0.5"
            }, duration, 'easeOutBounce');
        }
        div.removeClass("other").addClass("current").animate({
            width: "600px",
            opacity: "1"
        }, duration, 'easeOutBounce');
    }
}

小提琴

您正在调用函数而没有将其传递给setTimeout。我还改变了一些东西,以便轻松检索div。新函数返回一个函数调用,这个新函数可以访问第一个函数的参数。