setTimeout 函数不会在第一次鼠标输入/悬停时触发

setTimeout function not triggering on first mouseenter / hover

概览: 我正在创建一个菜单,当您将鼠标悬停在具有 class 'showhim' 的列表项上时,该菜单会显示 div 'showme'。我希望在列表项之间切换时有延迟,所以我包含了一个 setTimeout 函数。

问题: setTimeout 函数没有在第一个 mouseenter 事件上被触发。如果我删除 setTimeout 函数,则 mouseenter 事件可以正常工作。 鼠标输入

尝试过: 我试过 mouseover 和 mouseout 看看它是否会有所作为。如果我将鼠标放在跨度(菜单项名称)上,则会触发 setTimeout 函数。

另外,当我在最上面的父 div 上放置一个边框并在进入 'showhim' 之前将鼠标悬停在边框上时,触发了 setTimeout 函数并且菜单工作正常。我不知道为什么边框会让它起作用..

// Fake these for the snippet
var isHomepage = false;
function isMobile() {
    return false;
}
// End of fake
$('.showhim').mouseenter(function() {
  if (!isMobile()) {
    var $this = $(this);
    timer = setTimeout(function() {

      $('.mastermenuitem').removeClass('menu-active');
      $('.mainmenuitem').removeClass('nav-active');
      $('.showme').css('display', 'none');

      // Expand Shop Menu Container
      if (isHomepage && !isMobile()) {
        var corecenter_width = $('#corecenter').innerWidth();
        $('#shop-menu-container').css('width', corecenter_width - (border_width * 2));
      }

      // Add active class to clicked menu item
      $this.find('li').addClass('menu-active');
      $this.find('.showme').css('display', 'block');
      $this.find('.mainmenuitem').addClass('nav-active');
    }, 150);
  }
}).mouseleave(function() {
  clearTimeout(timer);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
   <!-- setTimeout triggered when hovering over shop-menu-container border -->
<div id="shop-menu-container">
<div class="menu-wrapper">
<div class="showmemaster">
  <div class="showhim-wrapper"> 
    <!-- Trigger Element-->
    <div class="showhim"> 
      <!-- mouseover works the first time when hovering over the span -->
      <ul><li class="mainmenuitem"><span>Menu Item 1</span></li></ul>
      <div class="showme" style="display:none;"> 
        Content 1
      </div>
    </div>

 <div class="showhim"> 
      <ul><li class="mainmenuitem"><span>Menu Item 2</span></li></ul>
      <div class="showme" style="display:none;"> 
        Content 2
      </div>
    </div>
  </div>
</div>

已解决: 我有 2 个 setTimeout 函数引用相同的计时器变量。

我所做的只是创建了另一个计时器并且悬停正常工作。

var timer; // setTimeout for Menu Close 
var timer2; // setTimeout for Showhim 

// TIMER 2
$('.showhim').mouseenter(function() {

  // Do something

    }, showhim_timeout);
}).mouseleave(function() {
    clearTimeout(timer2);
});


// TIMER 1
function timeoutMenu() {
    timer = setTimeout(function() {
        close();
    }, menu_timeout);

}

function stopTimeout() {
    clearTimeout(timer);
}