Cross-browser multi-line text overflow with ellipsis appended within a fixed width and height

前端 未结 25 2860
栀梦
栀梦 2020-11-22 16:19

I made an image for this question to make it easier to understand.

Is it possible to create an ellipsis on a

with a fixed width and multiple
25条回答
  •  佛祖请我去吃肉
    2020-11-22 16:40

    Pure JS demo (without jQuery and 'while' loop)

    When I searched solution of multiline ellipsis problem I was surprised that there is no any good one without jQuery. Also there are a few solutions based on 'while' loop, but I think they are not effective and dangerous due to possibility to get into infinite loop. So I wrote this code:

    function ellipsizeTextBox(el) {
      if (el.scrollHeight <= el.offsetHeight) {
        return;
      }
    
      let wordArray = el.innerHTML.split(' ');
      const wordsLength = wordArray.length;
      let activeWord;
      let activePhrase;
      let isEllipsed = false;
    
      for (let i = 0; i < wordsLength; i++) {
        if (el.scrollHeight > el.offsetHeight) {
          activeWord = wordArray.pop();
          el.innerHTML = activePhrase = wordArray.join(' ');
        } else {
          break;
        }
      }
    
      let charsArray = activeWord.split('');
      const charsLength = charsArray.length;
    
      for (let i = 0; i < charsLength; i++) {
        if (el.scrollHeight > el.offsetHeight) {
          charsArray.pop();
          el.innerHTML = activePhrase + ' ' + charsArray.join('')  + '...';
          isEllipsed = true;
        } else {
          break;
        }
      }
    
      if (!isEllipsed) {
        activePhrase = el.innerHTML;
    
        let phraseArr = activePhrase.split('');
        phraseArr = phraseArr.slice(0, phraseArr.length - 3)
        el.innerHTML = phraseArr.join('') + '...';
      }
    }
    
    let el = document.getElementById('ellipsed');
    
    ellipsizeTextBox(el);
    

提交回复
热议问题