在`onClick`上切换DIV高度

时间:2014-05-20 09:05:16

标签: jquery html css

我想切换分区的高度。我尝试过使用.animate和if / else语句。但它会反弹回来。 现在使用的代码将隐藏我的部门而不是切换高度。它会在点击时触发。

$(document).ready(function() {
       $("#content1").toggle(function(){
         $(this).animate({height:'400px'});
   }, function() {
         $(this).animate({height:'200px'});
   });
});

我希望有人能得到答案,因为我无法在google / stackoverflow上找到答案。

2 个答案:

答案 0 :(得分:4)

为什么不直接使用.animate()来设置div的高度,并在每次单击div时为更改设置动画!

像:

$( "div" ).click(function() {
    if ( $(this).height() != 50)
          $( this ).animate({ height: 50 }, 1000 );
    else
          $( this ).animate({ height: 100 }, 1000 );
});

这是一个完整的例子:http://jsfiddle.net/62jcH/3/

答案 1 :(得分:1)

您可以添加一个数据点击属性,该属性将存储可用于选择正确动画的点击次数 - 偶数/奇数。

$(document).ready(function() {
   $('#content1').data( 'clicks', 0 );
   $("#content1").on( 'click', function() {
      var clicks = +$( this ).data( 'clicks' );
      if( clicks % 2 === 0 ) {
         $(this).animate({height:'400px'});
      } else {
         $(this).animate({height:'200px'});
      }
      $( this ).data( 'clicks', clicks + 1 );
   });
});

或者,你可以编写一个jQuery插件,而不是点击事件。

相关问题