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

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

    Here's a vanilla JavaScript solution you can use in a pinch:

    // @param 1 = element containing text to truncate
    // @param 2 = the maximum number of lines to show
    function limitLines(el, nLines) {
      var nHeight,
        el2 = el.cloneNode(true);
      // Create clone to determine line height
      el2.style.position = 'absolute';
      el2.style.top = '0';
      el2.style.width = '10%';
      el2.style.overflow = 'hidden';
      el2.style.visibility = 'hidden';
      el2.style.whiteSpace = 'nowrap';
      el.parentNode.appendChild(el2);
      nHeight = (el2.clientHeight+2)*nLines; // Add 2 pixels of slack
      // Clean up
      el.parentNode.removeChild(el2);
      el2 = null;
      // Truncate until desired nLines reached
      if (el.clientHeight > nHeight) {
        var i = 0,
          imax = nLines * 35;
        while (el.clientHeight > nHeight) {
          el.innerHTML = el.textContent.slice(0, -2) + '…';
          ++i;
          // Prevent infinite loop in "print" media query caused by
          // Bootstrap 3 CSS: a[href]:after { content:" (" attr(href) ")"; }
          if (i===imax) break;
        }
      }
    }
    
    limitLines(document.getElementById('target'), 7);
    #test {
      width: 320px;
      font-size: 18px;
    }

    Paragraph 1

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    Paragraph 3

    You can play around with it in the codepen below. Try changing the font size in the CSS panel and make a minor edit in the HTML panel (e.g., add an extra space somewhere) to update the results. Regardless of the font size, the middle paragraph should always be truncated to the number of lines in the second parameter passed to limitLines().

    Codepen: http://codepen.io/thdoan/pen/BoXbEK

提交回复
热议问题