HTML+CSS:展开动画
要实现一个简单的HTML和CSS展开动画,你可以使用CSS的transition属性和一些JavaScript代码。以下是一个例子:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Expand Animation</title>
<style>
.container {
overflow: hidden;
max-height: 0;
transition: max-height 0.3s ease-out;
background-color: #f5f5f5;
padding: 10px;
margin-top: 10px;
}
.read-more .btn {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
text-align: center;
display: inline-block;
font-size: 16px;
cursor: pointer;
}
.read-more .content {
display: none;
}
</style>
</head>
<body>
<div class="read-more">
<button class="btn">Read More</button>
<div class="content">
<p>This is the content that will be revealed when you click the button. It can be any text or HTML content you want to show.</p>
</div>
</div>
<script>
document.querySelector('.read-more .btn').addEventListener('click', function() {
var content = document.querySelector('.read-more .content');
content.style.display = 'block';
setTimeout(function() {
content.classList.add('container');
}, 0);
});
</script>
</body>
</html>
CSS:
.container {
overflow: hidden;
max-height: 0;
transition: max-height 0.3s ease-out;
background-color: #f5f5f5;
padding: 10px;
margin-top: 10px;
}
.read-more .btn {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
text-align: center;
display: inline-block;
font-size: 16px;
cursor: pointer;
}
.read-more .content {
display: none;
}
JavaScript:
document.querySelector('.read-more .btn').addEventListener('click', function() {
var content = document.querySelector('.read-more .content');
content.style.display = 'block';
setTimeout(function() {
content.classList.add('container');
}, 0);
});
这段代码实现了一个按钮点击后内容逐渐展开的效果。通过CSS定义了.container
类的初始最大高度为0,并设置了过渡效果。当JavaScript代码监听到按钮点击事件时,它会将内容的display属性设置为'block',并在下一个事件循环中添加.container
类,从而触发最大高度从0到实际内容高度的过渡动画。
评论已关闭