要精准计算包含换行符的文本行数并动态显示“展开”按钮,可以通过以下步骤实现:
首先,我们需要计算文本的行数。可以通过以下方法来实现:
textarea
元素:将文本放入 textarea
元素中,然后通过 textarea
的 scrollHeight
和 lineHeight
来计算行数。div
元素:将文本放入 div
元素中,设置 white-space: pre-wrap
或 white-space: pre-line
来保留换行符,然后通过 div
的 clientHeight
和 lineHeight
来计算行数。根据计算的行数,动态决定是否显示“展开”按钮。如果行数超过某个阈值(例如3行),则显示“展开”按钮。
以下是一个使用 div
元素的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态显示展开按钮</title>
<style>
.text-container {
width: 300px;
border: 1px solid #ccc;
padding: 10px;
white-space: pre-line; /* 保留换行符 */
line-height: 1.5; /* 设置行高 */
overflow: hidden; /* 超出部分隐藏 */
}
.expand-button {
display: none; /* 默认隐藏 */
color: blue;
cursor: pointer;
margin-top: 5px;
}
</style>
</head>
<body>
<div class="text-container" id="textContainer">
这是一个包含换行符的文本。
这是第二行。
这是第三行。
这是第四行。
这是第五行。
</div>
<div class="expand-button" id="expandButton">展开</div>
<script>
function calculateLines() {
const textContainer = document.getElementById('textContainer');
const lineHeight = parseInt(window.getComputedStyle(textContainer).lineHeight, 10);
const containerHeight = textContainer.clientHeight;
const lines = Math.round(containerHeight / lineHeight);
return lines;
}
function toggleExpandButton() {
const lines = calculateLines();
const expandButton = document.getElementById('expandButton');
if (lines > 3) {
expandButton.style.display = 'block';
} else {
expandButton.style.display = 'none';
}
}
// 初始化时检查是否需要显示展开按钮
toggleExpandButton();
// 监听窗口大小变化,重新计算行数
window.addEventListener('resize', toggleExpandButton);
// 点击展开按钮时显示全部内容
document.getElementById('expandButton').addEventListener('click', function() {
const textContainer = document.getElementById('textContainer');
textContainer.style.overflow = 'visible';
textContainer.style.height = 'auto';
this.style.display = 'none';
});
</script>
</body>
</html>
HTML 结构:
text-container
:用于显示文本的容器。expand-button
:用于展开文本的按钮,默认隐藏。CSS 样式:
white-space: pre-line
:保留换行符。line-height: 1.5
:设置行高。overflow: hidden
:超出部分隐藏。JavaScript 逻辑:
calculateLines
:计算文本的行数。toggleExpandButton
:根据行数决定是否显示“展开”按钮。line-height
的值是固定的,否则计算可能会有误差。toggleExpandButton
函数。通过以上方法,你可以精准计算包含换行符的文本行数,并根据行数动态显示“展开”按钮。