html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Expand/Collapse</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="text-container">
<div class="text" id="text">
这是一段非常长的文本,用于展示展开和收起的功能。这段文本很长,以至于在默认情况下不能完全显示在页面上。
</div>
<button class="btn" id="expandBtn">展开</button>
<button class="btn" id="collapseBtn" style="display: none;">收起</button>
</div>
<script src="script.js"></script>
</body>
</html>
css
/* styles.css */
.text-container {
width: 300px;
margin: 20px auto;
text-align: center;
}
.text {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3; /* 显示前3行 */
-webkit-box-orient: vertical;
transition: max-height 0.3s ease-out;
}
.btn {
margin-top: 10px;
padding: 10px 20px;
cursor: pointer;
}
transition
属性用于添加动画效果,使文本展开和收起更加平滑。
js
// script.js
document.addEventListener('DOMContentLoaded', function () {
const textElement = document.getElementById('text');
const expandBtn = document.getElementById('expandBtn');
const collapseBtn = document.getElementById('collapseBtn');
// 初始状态最大高度设为3行文本的高度(假设每行大约20px,可以根据实际情况调整)
let maxHeight = textElement.scrollHeight;
textElement.style.maxHeight = `${3 * 20}px`; // 假设每行文本高度为20px
expandBtn.addEventListener('click', function () {
textElement.style.maxHeight = maxHeight + 'px';
expandBtn.style.display = 'none';
collapseBtn.style.display = 'inline-block';
});
collapseBtn.addEventListener('click', function () {
textElement.style.maxHeight = `${3 * 20}px`; // 恢复为3行的高度
expandBtn.style.display = 'inline-block';
collapseBtn.style.display = 'none';
});
});