Jquery - 动画高度切换

We'*_*ars 38 jquery height attr jquery-animate

我在屏幕顶部有一个10px的条,当点击时,我希望它的动画高度为40px,然后再次点击,动画回到10px.我尝试更改div的id,但它不起作用.我怎么能让这个工作,或者有更好的方法来做到这一点?

身体html:

<div id="topbar-show"></div>

CSS:

#topbar-show { width: 100%; height: 10px; background-color: #000; }
#topbar-hide { width: 100%; height: 40px; background-color: #000; }
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

$(document).ready(function(){
  $("#topbar-show").click(function(){
    $(this).animate({height:40},200).attr('id', 'topbar-hide');
  });
  $("#topbar-hide").click(function(){
    $(this).animate({height:10},200).attr('id', 'topbar-show');
  });
});
Run Code Online (Sandbox Code Playgroud)

Ian*_*ers 56

尝试一下:

$(document).ready(function(){
  $("#topbar-show").toggle(function(){
    $(this).animate({height:40},200);
  },function(){
    $(this).animate({height:10},200);
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 请注意,自jQuery 1.9.1以来,这种切换已被弃用,并且不会像以前那样工作.对于版本> = 1.9.1,[沿着这些行的东西将起作用](http://stackoverflow.com/a/4965040/1813830) (6认同)

use*_*716 17

您可以使用toggle-event(docs)方法分配2个(或更多)处理程序,以便在每次单击时切换.

示例: http ://jsfiddle.net/SQHQ2/1/

$("#topbar").toggle(function(){
    $(this).animate({height:40},200);
},function(){
    $(this).animate({height:10},200);
});
Run Code Online (Sandbox Code Playgroud)

或者您可以创建自己的切换行为:

示例: http ://jsfiddle.net/SQHQ2/

$("#topbar").click((function() {
    var i = 0;
    return function(){
        $(this).animate({height:(++i % 2) ? 40 : 10},200);
    }
})());
Run Code Online (Sandbox Code Playgroud)

  • + upvote:@ user113716:你可以详细讲解(第二个解决方案) (2认同)

Nat*_*son 16

您应该使用a class来实现您想要的:

CSS:

#topbar { width: 100%; height: 40px; background-color: #000; }
#topbar.hide { height: 10px; }
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

  $(document).ready(function(){
    $("#topbar").click(function(){
      if($(this).hasClass('hide')) {
        $(this).animate({height:40},200).removeClass('hide');
      } else { 
        $(this).animate({height:10},200).addClass('hide');
      }
    });
  });
Run Code Online (Sandbox Code Playgroud)