从hover切换到点击?

我最近在我的网站上在页面底部实现了一个小盒子,当鼠标hover在它上面时进行扩展…这是代码,一切都很好。

CSS

#box{ position:absolute; width:300px; height:20px; left: 33%; right: 33%; min-width: 32%; bottom:0; background-color: #353535; } 

JavaScript的

 $('#box').hover(function() { $(this).animate({ height: '220px' }, 150); },function() { $(this).animate({ height: '20px' }, 500); }); 

但是我很好奇我是如何改变它来打开和关闭点击而不是鼠标hover在它上面?

我把它编辑成……

 $('#box').click(function() { $(this).animate({ height: '220px' }, 150); },function() { $(this).animate({ height: '20px' }, 500); }); 

这可以打开盒子。 但我无法通过另一次点击再次关闭它。

到目前为止如此接近! :P

这应该工作

 $('#box').toggle(function() { $(this).animate({ height: '220px' }, 150); },function() { $(this).animate({ height: '20px' }, 500); }); 

你可以只使用toggle事件处理程序而不是click事件,如下所示:

 $('#box').toggle(function() {...}, function() {...}); 

你可以做:

 $('#box').click(function() { if ($(this).is(':visible')) { $(this).hide(); return; } $(this).animate({height: '220px'}, 150); }); 

在单击时,它将隐藏元素(如果可见),否则为其设置动画。