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

前端 未结 25 2436
栀梦
栀梦 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:38

    Pure JS solution based on bažmegakapa's solution, and some cleanup to account for people who try to give a height/max-height that is less than the element's lineHeight:

      var truncationEl = document.getElementById('truncation-test');
      function calculateTruncation(el) {
        var text;
        while(el.clientHeight < el.scrollHeight) {
          text = el.innerHTML.trim();
          if(text.split(' ').length <= 1) {
            break;
          }
          el.innerHTML = text.replace(/\W*\s(\S)*$/, '...');
        }
      }
    
      calculateTruncation(truncationEl);
    

提交回复
热议问题