要实现多行文本省略并在用户交互时显示完整文本及按钮,可以结合CSS和JavaScript来实现。以下是一个优雅的解决方案:
首先,使用CSS的-webkit-line-clamp
属性来实现多行文本省略。这个属性可以限制在一个块级元素中显示的文本行数。
<div class="text-container">
<p class="text-content">这是一段很长的文本,需要在一定高度后省略并显示“查看更多”按钮。</p>
<button class="show-more-btn">查看更多</button>
</div>
.text-container {
width: 300px; /* 设置容器宽度 */
position: relative;
}
.text-content {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3; /* 限制显示3行 */
overflow: hidden;
text-overflow: ellipsis;
line-height: 1.5; /* 设置行高 */
}
.show-more-btn {
display: none; /* 初始状态下隐藏按钮 */
position: absolute;
bottom: 0;
right: 0;
background-color: white;
border: none;
cursor: pointer;
color: blue;
}
接下来,使用JavaScript来控制按钮的显示和隐藏,并在用户点击按钮时展开文本。
document.addEventListener('DOMContentLoaded', function() {
const textContent = document.querySelector('.text-content');
const showMoreBtn = document.querySelector('.show-more-btn');
// 检查文本是否溢出
if (textContent.scrollHeight > textContent.clientHeight) {
showMoreBtn.style.display = 'block'; // 显示“查看更多”按钮
}
// 点击按钮时展开文本
showMoreBtn.addEventListener('click', function() {
textContent.style.webkitLineClamp = 'unset'; // 取消行数限制
showMoreBtn.style.display = 'none'; // 隐藏按钮
});
});
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>多行文本省略及按钮显示</title>
<style>
.text-container {
width: 300px;
position: relative;
}
.text-content {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
text-overflow: ellipsis;
line-height: 1.5;
}
.show-more-btn {
display: none;
position: absolute;
bottom: 0;
right: 0;
background-color: white;
border: none;
cursor: pointer;
color: blue;
}
</style>
</head>
<body>
<div class="text-container">
<p class="text-content">这是一段很长的文本,需要在一定高度后省略并显示“查看更多”按钮。这是一段很长的文本,需要在一定高度后省略并显示“查看更多”按钮。这是一段很长的文本,需要在一定高度后省略并显示“查看更多”按钮。</p>
<button class="show-more-btn">查看更多</button>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const textContent = document.querySelector('.text-content');
const showMoreBtn = document.querySelector('.show-more-btn');
if (textContent.scrollHeight > textContent.clientHeight) {
showMoreBtn.style.display = 'block';
}
showMoreBtn.addEventListener('click', function() {
textContent.style.webkitLineClamp = 'unset';
showMoreBtn.style.display = 'none';
});
});
</script>
</body>
</html>
-webkit-line-clamp
属性限制文本显示的行数,并通过overflow: hidden
和text-overflow: ellipsis
实现省略号显示。scrollHeight
和clientHeight
来判断文本是否溢出,如果溢出则显示“查看更多”按钮。点击按钮后,取消行数限制并隐藏按钮。-webkit-line-clamp
在现代浏览器中支持良好,但在某些旧版浏览器中可能不支持。如果需要兼容性更好的解决方案,可以考虑使用JavaScript动态计算文本高度并截断文本。通过这种方式,你可以优雅地实现多行文本省略及按钮显示的功能。