我正在尝试在应用类后为元素的高度设置动画,这是简化的代码:
HTML
<div class="section">
<div class="panel">
<a href="#" class="toggle">Click</a>
<div class="panel-content">
Some content...
</div>
</div>
</div>
CSS
.section {
position: relative;
width: 500px;
height: 200px;
margin: 100px auto;
background: #ccc;
}
.panel {
width: 65%;
position: absolute;
left: 0;
bottom: 0;
}
.toggle {
display: inline-block;
height: 15px;
background: #ddd;
}
.panel-content {
max-height: 0;
overflow: hidden;
transition: max-height 1s;
}
.active .panel-content {
max-height: 9999px;
}
JS
$(function() {
$('.toggle').on('click', function (e) {
e.preventDefault();
$(this).closest('.panel').toggleClass('active');
});
});
当我单击 .toggle
链接时,在 .panel
元素上设置了一个 active
类来激活 .panel- content
高度,但是当第一次添加类时,内容显示时没有动画,当它被删除时,元素需要一秒钟(过渡的持续时间)才能开始动画。您可以在此处观看现场演示:http://codepen.io/javiervd/pen/bLhBa
我也尝试使用 position 和 overflow 属性,但我无法让它工作,也许有另一种方法可以达到相同的效果?
提前致谢。
最佳答案
你需要做一个 transition
当事情发生时。这不是你想要的,但让我给你看一些东西:
.pannel-content{
height:0;
}
.pannel-content:hover{
height:50px; transition:height 2s;
}
这就是transition
作品。您尚未创建操作。没有 click 伪类,您也不想影响相同的元素。尝试使用 jQuery,例如。
<html>
<head>
<style type='text/css'>
.active .pannel-content{
display:none; height:9999px;
}
</style>
</head>
<body>
<div class='section'>
<div class='panel'>
<a href='#' class='toggle'>Click</a>
<div class='panel-content'>
Some content...
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type='text/javascript'>
$('.toggle').click(function(){
$('.active .pannel-content').show('slow');
});
</script>
</body>
</html>
您还可以使用 jQuery 的 .animate()
方法。当然,我建议您使用 declair a DOCTYPE 并使用 <meta>
标签。您还应该使用外部 CSS,因为它会缓存在您的用户浏览器内存中。
访问http://api.jquery.com/show/和 http://api.jquery.com/animate/了解详情。
关于最大高度上的 CSS3 动画无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17255161/