<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
/* 两行省略号 */
.text-ellipsis-2 {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
.ellipsis-more {
position: relative;
height: 65px;
line-height: 2;
background-color: white;
}
/* 省略号自定义字符 */
.ellipsis-more-text {
display: none;
position: absolute;
right: 0;
bottom: 0;
background-color: inherit;
color: red;
}
</style>
</head>
<body>
<div class="text-ellipsis-2 ellipsis-more">
Hello everyone! To celebrate the launch of the IPL Official X (Twitter)
Account @the_ipl_com, we are hosting a Follow & Comment Giveaway, with a
total prize pool of $88 in USDT!<span class="ellipsis-more-text">...More</span>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.slim.js"></script>
<script>
/**
* 省略号显示自定义字符
*/
function ellipsisMoreText() {
function fun() {
$(".ellipsis-more-text").each((_, item) => {
const el = $(item).parent();
const el_height = $(el).height();
const t = document.createElement("span");
t.style = `
display: inline-block;
position: absolute;
width: 100%;
opacity: 0;
`;
t.innerHTML = $(el).text();
$(el).append(t);
const t_height = $(t).height();
$(t).remove();
if (t_height > el_height) $(item).show();
else $(item).hide();
});
}
fun();
window.addEventListener("resize", function () {
fun();
});
}
ellipsisMoreText();
</script>
</body>
</html>
通过比较文本的实际高度 (scrollHeight) 和容器的最大高度 (maxHeight) 来判断文本是否超出容器范围。如果文本被截断,则显示“查看更多”按钮;否则,隐藏该按钮。
js 截取自定内容长度,空格算在内,保留完整单词
function truncateText(text, maxLength) {
if (text.length <= maxLength) {
// 如果文本长度小于等于最大长度,则直接返回原字符串
return text;
}
// 截取从开始到maxLength的子串
let truncated = text.substring(0, maxLength);
// 查找最后一个空格的位置,确保单词完整
let lastSpaceIndex = truncated.lastIndexOf(' ');
if (lastSpaceIndex === -1 || lastSpaceIndex === 0) {
// 如果没有找到空格,或者空格位于开头,则返回原始截取的结果
// 这可能意味着整个单词超过了maxLength,因此我们无法避免截断单词
return truncated + '...';
} else {
// 返回截取到上一个空格为止的字符串,并加上省略号表示被截断
return truncated.substring(0, lastSpaceIndex) + '...';
}
}
let sampleText = "Michael Bracewell will captain New Zealand in their upcoming five-match T20I series against Pakistan. Bracewell also led the Black Caps during their tour of Pakistan last year, where the series ended in a 2-2 draw. ";
let result = truncateText(sampleText, 30);
console.log(result);