绑定带有褪色的鼠标事件



我使用以下代码在鼠标悬停在菜单项上的图像之间淡入…

 $(document).ready(function() { 
      $('nav li').each(function() {
          var bgPos = $(this).css('background-position');
          $(this).css('background-position', bgPos);
          $(this).removeAttr('id');
          bgPos = bgPos.split(' ');
          var position = $(this).position();
          var cssObj = {
            'position' : 'absolute',
            'top' : position.top,
            'left' : position.left,
            'background-position' : bgPos[0]+' -115px'
          }
          var outcome = $('<li></li>').hide();
          $(outcome).css(cssObj);
          $(this).parents('.nav').append(outcome);
          $(this).data('clone', outcome);
          $(this).bind({
            mouseenter: function() {
              $(this).data('clone').fadeIn(1000);
            },
            mouseout: function() {
              $(this).data('clone').fadeOut(300);
            }
          });
      });
});

问题是,当淡出完成时,淡出元素的显示变为none, jQuery认为我已经再次进入鼠标,即使我的鼠标没有移动,我结束了一个无尽的循环淡出然后淡出

绑定到克隆的mouseOut事件,而不是您的原始元素:

$(this).bind({
    mouseenter: function() {
          $(this).data('clone').fadeIn(1000);
    }});
outcome.bind({
    mouseout: function() {
          outcome.fadeOut(300);
    }});

您可能需要调整绑定到克隆的mouseOut事件的时间或您的HTML元素的确切布局,但这是一般的想法

最新更新