【问题标题】:jquery .hover, then .click to animate troublejquery .hover,然后 .click 动画麻烦
【发布时间】:2013-03-22 19:46:45
【问题描述】:

更新:我已合并我的代码并尝试添加 if/else 语句。我还没有弄清楚如何在点击时忽略 mouseenter/mouseleave 函数

$('#storybtn').on({
mouseenter:function(){
    $('#story')
        .stop()
        .animate({top:'405px'},'slow');
},
mouseleave:function(){
    $('#story')
        .stop()
        .animate({top:'435px'},'slow');
},
click:function(){
    var position = $('#story').css('top');
    if (position>'10px'){
    $('#story')
        .stop()
        .animate({top:'10px'},'slow');
        }
    else (position='10px'){
    $('#story')
        .stop()
        .animate({top:'435px'},'slow');
        }
    }
});

【问题讨论】:

    标签: jquery click hover if-statement


    【解决方案1】:

    我已经为你创建了一个示例小提琴:

    Example Fiddle

    为了避免发生点击后的鼠标离开动画,我在#story 中添加了一个类点击,并添加了一个 if/else 案例来检查它或在鼠标离开后将其删除:

     $('#storybtn').on({
            mouseenter: function () {
                $('#story')
                    .stop()
                    .animate({top: '405px'}, 'slow');
            },
            mouseleave: function () {
                if (!$('#story').hasClass('clicked')) {
                $('#story')
                    .stop()
                    .animate({top: '435px'}, 'slow');
                } else {
                    $('#story').removeClass('clicked')
                }
            },
            click: function () {
                var position = $('#story').css('top');
                if (position > '10px') {
                    $('#story')
                        .addClass('clicked')
                        .stop()
                        .animate({top: '10px'}, 'slow');
                } else if (position === '10px') {
                    $('#story')
                        .addClass('clicked')
                        .stop()
                        .animate({top: '435px'}, 'slow');
                }
            }
        });
    

    【讨论】:

      【解决方案2】:

      首先,您的 .hover() 语法已被较新版本的 jQuery 弃用。其次,您需要在激活新动画之前停止其他动画,否则它只会排队等待之前的动画完成。试试这个:

      $('#storybtn').on({
          mouseenter:function(){
              $('#story')
                  .stop()
                  .animate({top:'405px'},'slow');
          },
          mouseleave:function(){
              $('#story')
                  .stop()
                  .animate({top:'435px'},'slow');
          },
          click:function(){
              $('#story')
                  .stop()
                  .animate({top:'10px'},'slow');
          }
      });
      

      这利用了.on() 处理程序,这是.click().hover() 的简写。通过使用真实的东西,您可以整合您的代码。

      【讨论】:

      • .on 效果更好,但是当我单击鼠标时,鼠标落在后面并破坏了 div 平面,它会自动回滚。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      • 2012-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多