2014-10-17 66 views
2

我想弄清楚为什么我的悬停功能是怪异的。当您将鼠标悬停在某个div上时,另一个div将变为可见。但是,当我将光标向下移动到可见的div时,它会淡出并再次消失。这不应该发生,应该保持可见,直到我的光标离开主容器。悬停动画jQuery的多次发射

这是我的代码。

HTML

<div id="searchWrapper" class="fleft"> 
    <div class="box">Hover here!</div> 
    <div class="searchLinks" style="display: none;"> 
     <form id="search_mini_form" action="" method="get"> 
      <div class="form-search"> 
       <label for="search">Search:</label> 
       <input id="search" type="text" name="q" value="" class="input-text" maxlength="128" autocomplete="off"> 
       <button type="submit" title="Search" class="button"><span><span>Search</span></span></button> 
       <div id="search_autocomplete" class="search-autocomplete" style="display: none;"></div> 
       <script type="text/javascript"> 
        //<![CDATA[ 
        var searchForm = new Varien.searchForm('search_mini_form', 'search', ''); 
        searchForm.initAutocomplete('http://removed.com/index.php/catalogsearch/ajax/suggest/', 'search_autocomplete'); 
        //]]> 
       </script> 
      </div> 
     </form> 
    </div> 
</div> 

jQuery的

<script type="text/javascript"> 
    jQuery(function($) { 

     $("#searchWrapper").hover(
      function() { 
       $(".searchLinks").fadeIn(500); 
      }, 
      function() { 
       $(".searchLinks").fadeOut(500); 
      } 
     ); 

    }); 
</script> 

CSS

#searchWrapper { 
    position:relative; 
} 

#searchWrapper .searchLinks { 
    position: absolute; 
    z-index: 99999; 
    top: 50px; 
    background: #e7e7e7; 
    right: -145px; 
    display:none; 
    padding:10px; 
} 

#searchWrapper .box { 
    border:solid 1px #555; 
    padding: 20px 0px; 
    text-align:center; 
} 

这里你可以看到它是如何淡入,然后一旦你将鼠标悬停在上面,它就会消失并回到原来的状态。

http://jsfiddle.net/421g2cdh/7/

回答

8

必须使用stop()功能。

jQuery(function($) { 

    $("#searchWrapper").hover(
     function() { 
      $(".searchLinks").stop(true,true).fadeIn(500); 
     }, 
     function() { 
      $(".searchLinks").stop(true,true).fadeOut(500); 
     } 
    ); 

}); 

此外,减少.searchLinks的保证金,如果你不希望看到的,当鼠标它之间和它的父它淡出。 (填充顶,而不是顶部)

(见http://jsfiddle.net/421g2cdh/11/

+0

谢谢!工作很好。 – MagentoMan 2014-10-17 14:25:44

2

你徘徊的元素,你必须停止匹配元素当前正在运行的动画每次。

使用stop()

尝试:

jQuery(function($) { 

     $("#searchWrapper").hover(
      function() { 
       $(".searchLinks").stop().fadeIn(500); 
      }, 
      function() { 
       $(".searchLinks").stop().fadeOut(500); 
      } 
     ); 

    }); 

DEMO

1

使用stop(),你可以在使用输入/输出悬停的方法处理,因为它:

jQuery(function ($) { 
    $("#searchWrapper").hover(
    function() { 
     $(".searchLinks").stop().fadeToggle(500); 
    }); 
}); 

jsFiddle

fadeToggle()

+0

+1对于fadeToogle,但-1不回答真正的问题:) – FLX 2014-10-17 14:26:09

+0

正确,我甚至没有发现,不像你的答案;) – 2014-10-17 14:30:33

0

无上述工作对我来说,但我发现,只有触发一次使用.unbind()一个解决方案:

$("#sidebar").unbind().on('mouseenter', function() { 
    console.log('mouse entered sidebar'); 
});