简体   繁体   English

jQuery为具有min-height属性的元素设置高度动画?

[英]jQuery animate height on element with min-height property?

I have an element with a min-height of 300px set in CSS: 我在CSS中设置了一个最小高度为300px的元素:

<!-- HTML -->
<div id="summary"></div>
<div id="collapse"></div>
/* CSS */
#summary { min-height: 300px } 

When I click on the #collapse element, I would like the #summary element to collapse smoothly to a height of 100px. 当我单击#collapse元素时,我希望#summary元素平滑地折叠到100px的高度。

$("#collapse").click(function() {
   $("#summary").animate({ height: 100}, 1000);
}); 

However, nothing is happening, and I think that is because of the min-height property. 但是,什么也没有发生,我认为这是由于min-height属性。

I have read this discussion on the jQuery forums , but I still can't figure out how to make the #summary div animate smoothly - setting the min-height to auto as they suggest makes the div vanish and then reappear! 已经在jQuery论坛上阅读了此讨论 ,但是我仍然想不出如何使#summary div平滑地进行动画-将最小高度设置为auto,因为它们提示div消失,然后重新出现! Can anyone help? 有人可以帮忙吗?

UPDATE: I've made a jsFiddle to demonstrate the problem . 更新:我做了一个jsFiddle来演示问题

you could try to do something like 你可以尝试做类似的事情

$("#collapse").click(function() {
   var summary = $("#summary"),
       height  = summary.height();

   summary
     .css({ height: height + 'px', minHeight: 0 }) 
     .animate({ height: 100}, 1000);
});

The idea is to reset the min-height and set the css height property to the computed height of the element itself just before the animation. 这个想法是重置min-height并将css height属性设置为动画之前元素本身的计算高度。

You need to use height in css in instead of min-height as you decrease the height to 100 and min-height is 300 on click event. 您需要在css中使用height而不是min-height因为将click事件的高度降低到100且min-height是300。

Live Demo 现场演示

Change 更改

#summary { min-height: 300px } 

To

#summary { height: 300px; } 

If you need to use min-width then you need to change min-width in animate instead of height. 如果需要使用最小宽度,则需要更改动画中的最小宽度而不是高度。

try this out in the fiddle: http://jsfiddle.net/8jn7v/5/ 在小提琴中尝试一下: http : //jsfiddle.net/8jn7v/5/

change this: 改变这个:

height: 50

to this: 对此:

$('#summary').animate({ 
  'min-height': 50+'px' // <--see the quotes at min-height and add pixels to it
}, 1000);

min-height lets you not to decrease the height lesser than the min-height min-height可以使您减小的高度不小于min-height

your element is limited to 300px because of the min-height so you have to animate the min-height instead of height 由于min-height ,您的元素限制为300px ,因此您必须设置min-height而不是height动画

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM