简体   繁体   English

如何使用JavaScript和CSS为高度变化设置动画?

[英]How to animate a height change using javascript and css?

I have this image that gets revealed when clicked, but i would like there to be a transition animation of 1s or so. 我有单击该图像时会显示该图像,但是我希望有1s左右的过渡动画。

I don't want to use jQuery. 我不想使用jQuery。 A mobile friendly css solution would be great. 一个移动友好的CSS解决方案将是很棒的。

Any ideas? 有任何想法吗?

 #cover { height: 100px; overflow: hidden; border-radius: 4px 4px 0 0; } #image { width: 100%; display: block; } 
 <div class="cover" id="cover"> <img src="http://lorempixel.com/500/500/cats/" onclick="myFunction()" id="image" /> </div> <script> var isOpen = false; function myFunction() { var image = document.getElementById('image'); var cover = document.getElementById('cover'); if (isOpen === false) { cover.setAttribute("style", "height:" + image.offsetHeight + "px"); isOpen = true; } else if (isOpen !== false) { cover.setAttribute("style", "height:100px"); isOpen = false; } } </script> 

You can just add transition: height 1s to have a one second animation: 您可以只添加transition: height 1s来获得一秒钟的动画:

 #cover { height: 100px; overflow: hidden; border-radius: 4px 4px 0 0; -webkit-transition: height 1s; -moz-transition: height 1s; -ms-transition: height 1s; -o-transition: height 1s; transition: height 1s; } #image { width: 100%; display: block; } 
 <div class="cover" id="cover"> <img src="http://lorempixel.com/500/500/cats/" onclick="myFunction()" id="image" /> </div> <script> var isOpen = false; function myFunction() { var image = document.getElementById('image'); var cover = document.getElementById('cover'); if (isOpen === false) { cover.setAttribute("style", "height:" + image.offsetHeight + "px"); isOpen = true; } else if (isOpen !== false) { cover.setAttribute("style", "height:100px"); isOpen = false; } } </script> 

Theres a hacky way to do this without any JS at all. 完全没有任何JS的情况下,有一种骇人听闻的方法。 I used the max-height attribute, this way it could be used for images that does not have a fixed height. 我使用了max-height属性,这样它可以用于没有固定高度的图像。

 #cover { min-height:100px; max-height:100px; overflow:hidden; position:relative; transition: all linear 1s; } #coverToggle:checked + #cover { max-height:500px; } label { position:absolute; left:0px; top:0px; right:0px; bottom:0px; } input { position:absolute; visibility:hidden; top:-100px; left:-100px; } 
 <input type="checkbox" id="coverToggle" /> <div class="cover" id="cover"> <label for="coverToggle"></label> <img src="http://lorempixel.com/500/500/cats/" id="image" /> </div> 

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

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