2013-06-24 33 views
0

我正在使用以下内容来增加点击格的高度,但如果再次点击链接,我需要将高度改为原来的高度。如何减少div的高度onclick?

CODE:

$(document).ready(function() { 
    $('.anchor_clicker').click(function(){ 
    $('#increaseth_the_height').animate({height:'930'}) 
}) 
    }); 
+0

@ hjpotter92这仍然有效吗?根据[切换文档](http://api.jquery.com/toggle/),它不接受这些参数?根据[本文档](http://api.jquery.com/toggle-event/),它已被弃用。 – Precastic

回答

1

尝试将其存储对基于该元素&切换。这是假设你只有1个元素与.anchor_clicker类:​​

$(document).ready(function() { 
    $('.anchor_clicker').click(function(){ 
    if($('.anchor_clicker').data('stored-height') == 930) { 
     $('.anchor_clicker').data('stored-height','100'); 
     $('#increaseth_the_height').animate({height:'100'}) 
    } else { 
     $('.anchor_clicker').data('stored-height','930'); 
     $('#increaseth_the_height').animate({height:'930'}) 
    } 
    }) 
}); 
1

事情是这样的:

var isExpanded=false; 
$(document).ready(function() { 
    $('.anchor_clicker').click(function(){ 
    if(isExpanded==false) 
    { 
     $('#increaseth_the_height').animate({height:'930'}) 
     isExpanded=true 
    } else 
    { 
     $('#increaseth_the_height').animate({height:'ORIGANAL'}) 
     isExpanded=false 
    } 
}) 
    }); 
1

一种方式做到这一点是需要记住的“点击”状态,并做了if到确定是否缩小或放大DIV ...

$(document).ready(function() { 
    var clicked = 0; 
    $('.anchor_clicker').click(function(){ 
     if(clicked === 0){ 
      $('#increaseth_the_height').animate({height:'930'}) 
      clicked = 1; 
     } 
     else { 
      $('#increaseth_the_height').animate({height:'300'}) //or whatever the orig height was 
      clicked = 0; 
     } 
    }) 
}); 
1

我会添加一个,只是为了在有效率的说法:

$(function(){ 
    function animateHeight($item,ht,spd){ 
     $item.stop().animate({height:ht},spd); 
    } 

    $("#topbar-show").click(function(){ 
     $(this).toggle(function(){ 
      animateHeight($(this),40,200); 
     },function(){ 
      animateHeight($(this),10,200); 
     }); 
    }); 
}); 

我添加了.stop()方法来防止动画排队,并且在动画中创建了一个函数,它允许灵活地在任意数量的对象上使用动画。

如果.toggle()功能是不是你喜欢的,你总是可以使用一个类来代替:

$(function(){ 
    function animateHeight($item,ht,spd){ 
     $item.stop().animate({height:ht},spd); 
    } 

    $("#topbar-show").click(function(){ 
     if($(this).hasClass('clicked')){    
      $(this).removeClass('clicked'); 
      animateHeight($(this),10,200); 
     } else {     
      $(this).addClass('clicked');  
      animateHeight($(this),40,200); 
     } 
    }); 
}); 

我个人比较喜欢的类方法,但每一个自己。

+1

调用切换()已废弃1.8在1.9+不存在[见这里](http://api.jquery.com/toggle-event/) – Precastic

+0

是的,我不知道他用的是哪个版本的这种方式。我添加了基于类的方法,我也明确表示我偏好。 – PlantTheIdea