Tengo una barra de 10 px en la parte superior de la pantalla que, cuando se hace clic, quiero que se anime a una altura de 40 px y luego, si se vuelve a hacer clic, se anima de nuevo a 10 px. Intenté cambiar la identificación del div, pero no funciona. ¿Cómo podría hacer que esto funcione, o hay una mejor manera de hacerlo?
cuerpo 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; }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'); }); });Prueba esto:
$(document).ready(function(){ $("#topbar-show").toggle(function(){ $(this).animate({height:40},200); },function(){ $(this).animate({height:10},200); }); });Puede usar el método de toggle-event (docs) para asignar 2 (o más) controladores que alternan con cada clic.
Ejemplo: http://jsfiddle.net/SQHQ2/1/
$("#topbar").toggle(function(){ $(this).animate({height:40},200); },function(){ $(this).animate({height:10},200); });o puede crear su propio comportamiento de alternancia:
Ejemplo: http://jsfiddle.net/SQHQ2/
$("#topbar").click((function() { var i = 0; return function(){ $(this).animate({height:(++i % 2) ? 40 : 10},200); } })());Deberías estar usando una class para lograr lo que quieres:
CSS:
#topbar { width: 100%; height: 40px; background-color: #000; } #topbar.hide { height: 10px; }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'); } }); });