文本超出省略號之前后省略號實現


標簽:css js


前情

最近在做聊天記錄需求時,對於查到的消息體需要高亮顯示,前后內容超出需要顯示省略號,效果如下圖:

對於后省略號是可以通過的一串css來實現的,主要是css的代碼段如下:

/*css省略號代碼段*/
overflow: hidden;
text-overflow: ellipsis;
position: relative;
white-space: nowrap;

解決方案1

Javascript實現

實現原理

這是我一強悍同事提出的解決方法,通過的canvas去測試文本的長度,再用長度和當前容器比較,如果大於當前容器,則前省略號+手動截取前5個字+關鍵字+后面內容,再用css省略號代碼段去自動實現后面內容省略號。

關健代碼

<div id="container" style="width: 200px"></div>
#container {
    background-color: aquamarine;
    display: flex;
    flex-direction: column;
  }

  #container div {
    overflow: hidden;
    text-overflow: ellipsis;
    position: relative;
    white-space: nowrap;
  }
let keywords = "測試";
let container = document.querySelector('#container');
let containerWidth = container.offsetWidth;
wordList.forEach((word) => {
    let width = ctx.measureText(word).width;
    if (containerWidth > width) {
        container.appendChild(createSpan(word));
    } else {
        let ygIndex = word.indexOf(keywords);
        if (ygIndex > 5) {
            word = ' ...' + word.slice(ygIndex - 5);
        }
        container.appendChild(createSpan(word));
    }
})

function createSpan(word) {
    let span = document.createElement('div');
    span.innerText = word;
    return span;
}

完整測試地址

Css實現

實現原理

同事提供的方式是可行的,只是我考慮到通過canvas去繪會有一定成本,於是一直在思考是否可以通過純css來解決,猛的突然想到文本是可以控制方向的,於是通過把內容分成三段:前面文本+關鍵字+后面文本,改變第一段文字的文本渲染方向,再用css省略號代碼段去自動實現前后代碼的省略號

關鍵代碼

<div class="text_test">
  <span>這里是前面的內容哦,67890123456</span>
  <span>關鍵字</span>
  <span>這里是后面后文本哦,啦啦啦啦</span>
</div>
.text_test{
  display:flex;
  width:400px;
}
.text_test span{
  flex:0 1 auto;
  overflow:hidden;
  text-overflow:ellipsis;
  white-space:nowrap;
}
.text_test span:nth-of-type(1) {
  max-width: 180px;
  direction:rtl;
}
.text_test span:nth-of-type(2) {
  flex:none;
}

完整測試地址

最終實現

通過方式2實現,在提交代碼測試過程中發現通過改變文本方向的方式實現會對部分有方向的字符如“《》{}【】[]()”等會出現反轉還有對英文會改變位置等問題,最終考慮到成本和實現的必要,采用從關鍵字斷開,省略號+前5個字符+關鍵字+后面的字符來實現,如果你有更好的實現方式,歡迎留言。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM