【问题标题】:Hover event fires twice (on enter and leave) in jQuery?悬停事件在jQuery中触发两次(进入和离开)?
【发布时间】:2012-02-03 01:51:19
【问题描述】:
$(document).ready(function(){
    $("#menu a").hover(function(){
        $(this).animate({opacity: 0.25}, function(){
            $(this).animate({opacity: 1});
        });
    });
});

我将此效果应用于我的菜单,因此当鼠标移到链接上时,它会显示此淡入淡出效果,但当鼠标从链接中释放时,效果会再次播放。它不应该。它应该只在鼠标悬停在链接上时播放一次,而不是在鼠标离开时播放。

【问题讨论】:

    标签: jquery hover


    【解决方案1】:

    .hover() 有两个回调,一个用于mouseenter,一个用于mouseleave

    mouseenter 可能会更好:

    $(document).ready(function(){
        $("#menu a").mouseenter(function() {
            $(this).animate({opacity: 0.25}, function(){
                $(this).animate({opacity: 1});
            });
        });
    });
    

    【讨论】:

    • jQuery .hover() 事件处理 mouseentermouseleave,而不是 mouseovermouseout
    • @developius: .mouseover().on('mouseover') 的快捷方式
    • @Blender 是,但这不是推荐的方法,因为你不能像 diEcho 的回答那样做。
    • mouseenter 是正确的,根据文档:“当鼠标进入元素时”。
    【解决方案2】:

    jQuery v1.7

    试试这个
    $('#menu a').on({
        mouseover: function() {
            event.preventDefault();
            $(this).animate({opacity: 0.25});
        },
        mouseout: function() {
            event.preventDefault();
            $(this).animate({opacity: 1});
        }
    });
    

    working DEMO

    【讨论】:

      【解决方案3】:

      试试这个。在悬停事件上添加 $(this).stop()

         $(document).ready(function () {
                  $("#menu a").hover(function () {
                      $(this).animate({ opacity: 0.25 }, function () {
                          $(this).animate({ opacity: 1 });
                      });
                  }, function () { $(this).stop(); });
              });
      

      【讨论】:

        【解决方案4】:

        试试:

        $("#menu a").hover( function () { $(this).animate({opacity: 0.25}, function(){ $(this).animate({opacity: 1}); }); }, function () { //do nothing } );

        【讨论】:

          【解决方案5】:

          如果您想在悬停时触发一次,请改用 mouseenter:

          $("element").mouseenter(function(){
              //event here
          }); 
          

          【讨论】:

            【解决方案6】:

            你必须检查你是否得到相同的对象

            示例:

            $('#updateCart').on('mouseenter', function (event) {
                    if (event.handled !== true) { .....
                              //Put your code in here
                      }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2015-03-18
              • 1970-01-01
              • 1970-01-01
              • 2011-09-16
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多