文本超出省略號以前後省略號實現

標籤:css jsjavascript


前情

最近在作聊天記錄需求時,對於查到的消息體須要高亮顯示,先後內容超出須要顯示省略號,效果以下圖:css

對於後省略號是能夠經過的一串css來實現的,主要是css的代碼段以下:html

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

解決方案1

Javascript實現

實現原理java

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

關健代碼app

<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實現

實現原理flex

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

關鍵代碼code

<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;
}

完整測試地址

相關文章
相關標籤/搜索