jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。文字截断通常是指在网页上显示的文本长度超过一定限制时,通过省略号(...)来表示被截断的部分。
text-overflow: ellipsis;
实现文字截断。文字截断常用于以下场景:
假设我们有一个元素,初始状态下文本被截断显示,现在需要通过 jQuery 恢复完整的文本内容。
文本被截断通常是因为 CSS 属性 text-overflow: ellipsis;
和 white-space: nowrap;
的设置,导致文本超出容器宽度时被截断。
我们可以通过 jQuery 修改元素的 CSS 属性来恢复完整的文本内容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 恢复文字截断</title>
<style>
.truncated {
width: 200px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="truncated">这是一个非常长的文本,初始状态下会被截断显示。</div>
<button id="restore-btn">恢复完整文本</button>
<script>
$(document).ready(function() {
$('#restore-btn').click(function() {
$('.truncated').css({
'white-space': 'normal',
'text-overflow': 'clip',
'overflow': 'visible'
});
});
});
</script>
</body>
</html>
.truncated
类设置了 width
、white-space
、overflow
和 text-overflow
属性,使得文本在超出容器宽度时被截断。$('#restore-btn').click()
事件绑定,修改 .truncated
类的 CSS 属性:white-space: normal;
:允许文本换行。text-overflow: clip;
:不再显示省略号。overflow: visible;
:允许文本超出容器显示。通过这种方式,我们可以轻松地通过 jQuery 恢复被截断的文本内容。
领取专属 10元无门槛券
手把手带您无忧上云