【问题标题】:jQuery : How to create a jQuery hover function?jQuery:如何创建 jQuery 悬停功能?
【发布时间】:2010-09-27 12:43:52
【问题描述】:

我想创建两个函数来淡入和淡出一个元素。

这是我到目前为止所做的,但问题是如果你在悬停的元素中移动鼠标,它会开始振动:|我应该如何使它不振动并正常工作?

<script language="javascript" type="text/javascript">
 function hoverIn(target, speed){
     $(target).fadeIn(speed); 
 }

 function hoverOut(target, speed){
     $(target).fadeOut(speed); 
 }
</script>

LIVE PREVIEW - check out the problem in live

【问题讨论】:

    标签: jquery hover mouseover mouseout


    【解决方案1】:

    一个更好的方法是使用不显眼的脚本,你想要的主要是一个 .stop() 调用来停止以前的动画,像这样:

    <script type="text/javascript">
     function hoverIn(target, speed){
         $(target).stop(true, true).fadeIn(speed); 
     }
    
     function hoverOut(target, speed){
         $(target).stop(true, true).fadeOut(speed); 
     }
    </script>
    

    这仍然是个问题,因为mouseovermouseout 在进入/离开孩子时会触发。但是,.hover() 使用 mouseentermouseleave 不会遇到同样的问题,并且会消除您的“振动”问题。

    不显眼的版本如下所示:

    $(function() {
      $("ul > li").hover(function() {
        $(this).find("ul").stop(true, true).fadeIn('fast');
      }, function() {
        $(this).find("ul").stop(true, true).fadeOut('fast');
      });
    });​
    

    You can see it here,或者更短的版本:

    $(function() {
      $("ul > li").hover(function() {
        $(this).find("ul").stop(true, true).animate({opacity: 'toggle'}, 'fast');
      });
    });​
    

    You can test that here,请注意,所有这些不显眼的方法都不使用任何内联 javascript,并且适用于多个子菜单。

    【讨论】:

    • 您的第二个示例有效,但对我不利,因为我想要一个可用于任何元素的函数 :)
    • @CIRK - 因为mouseovermouseout 在进入孩子时会触发...你想要.hover() 这里使用mouseentermouseleave 哪个don' t 进入儿童时开火。如果您愿意,您仍然可以将其附加到单个元素。
    • 好吧,它可以在这里工作,非常感谢! :)
    猜你喜欢
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 2011-12-22
    • 2011-06-30
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多