遇到个工作上的需求,解决了,分享出来给有需要的小伙伴:
在两行放不下的情况下将中间文字省略号显示,保留头部和尾部显示。
思路:
获取刚开始的文字区域高度 height1
获取当前单行文字高度height2
切开字符串获得头部和尾部两个字符串
在height1>height2的时候执行循环依次移除头部的最后一位,直到高度符合
将头部的最后一位用省略号替换,拼接文字。
将拼接好的文字插入html
代码:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=0.5, user-scalable=no,viewport-fit=cover" />
<title>两行文字保持末尾固定文字显示,中间多余变为省略号</title>
</head>
<style>
.demo {
width: 80%;
font-size: 20px;
margin-left: 10%;
}
#txtcontent {
display: inline-block;
word-wrap: break-word;
word-break: break-all;
}
</style>
<body>
<div class="demo">
<div id="sigle" style="position: absolute;top:-100000px">测试文字高度</div>
<div id="txtcontent">十月过后的天空,猫坐在路边,你吹着风不说话就很甜。--张南</div>
</div>
</body>
<script>
let contentArea = document.getElementById('txtcontent');
let contentTxt = contentArea.innerHTML; //获取内容
let contentHeight = contentArea.clientHeight; //获取内容当前的高度
let sigleArea = document.getElementById('sigle'); //获取当前字体下单行文字高度
let sigleHeight = sigleArea.clientHeight;
let needHeight = sigleHeight * 2 //设置两行文字高度
setWordHeight()
function setWordHeight() {
if (contentHeight > needHeight) { //当文本高度大于设定的两行高度就执行
let j = 0
let beword = contentTxt.split("--")[0]
let afword = contentTxt.split("--")[1]
for (i = 0; needHeight < contentHeight; i++) {
contentTxt = contentArea.innerHTML;
beword = beword.substring(0, beword.length - 1);//每次删掉最后一个
contentArea.innerHTML = beword + " -- " + afword;//剩余的字符插入
contentHeight = contentArea.clientHeight;//重新计算高度
j++
if (j > 1000) {
return //防止出现意外卡死
}
}
//得到正好符合高度的文字,替换beword最后一个文字
let newText = beword.substring(0, beword.length - 1) + '...' + "<span style='color:blue'>" + " -- " + afword + "</span>";
contentArea.innerHTML = newText;
}
}
</script>
</html>