Replace hidden overflow with “…”

强颜欢笑 提交于 2019-12-06 04:09:56

I made a javascript function called hideOverflow which automatically hides the overflow and replaces it with an ellipsis.

function hideOverflow(element) {

  //Calculate lineHeight and maxLineCount for parent's height
  element.style.whiteSpace = 'nowrap';
  var parent = element.parentNode;
  var maxLineCount = Math.floor(parent.clientHeight / element.clientHeight);
  var maxLineHeight = element.clientHeight * maxLineCount;
  element.style.whiteSpace = 'normal';

  //Find and set maxLineHeight by replacing the overflow with an ellipses
  if (element.clientHeight > maxLineHeight) {
    var max = maxLineCount * element.style.lineHeight;
    for (var i = 0; element.clientHeight > maxLineHeight; i++) {
      element.innerHTML = element.textContent.slice(0, -2) + '…';
      i++;
      if (i === max) break;
    }
  }
}

hideOverflow(document.getElementById('foo'));
div {
      width: 300px;
      height: 100px;
      font-size: 18px;
      border: 1px black solid;
}

p {
  margin: 0px;
  padding: 0px;
}
<div>
  <p id="foo">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean et magna at sem tristique lobortis quis et nulla. Sed porttitor massa ac efficitur viverra. Donec eu commodo justo. Suspendisse libero quam, tincidunt non faucibus et, vehicula vel orci. Praesent in enim at odio ullamcorper gravida nec auctor diam. Aenean et feugiat quam. Donec sem felis, tristique et euismod at, elementum eget nulla.</p>
</div>

This does not support margin or padding currently, but you could easily adjust the Calculate lineHeight and maxLineCount for parent's height section of the hideOverflow function in order to achieve this same result with padding and margin.

Hope this helps!

The line-clamp property truncates text at a specific number of lines. Read more about line-clamp. Also: please check the browser support.

 p#event {
  --line-height: 1.4;
  --num-lines:2; /* 2 lines of text*/
  line-height:var(--line-height);
  display: block; /* Fallback for non-webkit */  
  max-width: 150px;
  height: calc(1em * var(--line-height) * var(--num-lines)); /*2 lines*/
  display: -webkit-box;
  -webkit-line-clamp: var(--num-lines);
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

You should add both conditions. You can check the demo in the fiddle.

p{
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

div{
width: 100px;
}
<div>
<p> Your text is long enough to  show this</p>
<p> Your text is long enough to  show this</p>
<p> Your text is long enough to  show this</p>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!