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

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

    I have made a version that leaves the html intact. jsfiddle example

    jQuery

    function shorten_text_to_parent_size(text_elem) {
      textContainerHeight = text_elem.parent().height();
    
    
      while (text_elem.outerHeight(true) > textContainerHeight) {
        text_elem.html(function (index, text) {
          return text.replace(/(?!(<[^>]*>))\W*\s(\S)*$/, '...');
        });
    
      }
    }
    
    $('.ellipsis_multiline').each(function () {
      shorten_text_to_parent_size($(this))
    });
    

    CSS

    .ellipsis_multiline_box {
      position: relative;
      overflow-y: hidden;
      text-overflow: ellipsis;
    }
    

    jsfiddle example

提交回复
热议问题