用“...”替换隐藏的溢出

Replace hidden overflow with "..."

javscript 中,我创建了一个将文本放入 div 的函数。但是,有时这段文字对于 div 来说太长了。所以在 css 中,我将溢出设置为隐藏。

overflow: hidden

我不只是不想显示这个溢出,而是想用“...”替换它,以便用户看到信息不完整。

我已经尝试计算字符串的长度,并在几个字符后停止计算,但由于我的 div 真的很窄,这似乎是一个很好的解决方案。

我该怎么做?

编辑:我想要多行,而不是一行

HTML:

<div id="event">This is way too much text for this div, but i want to show it partly</div>

CSS:

#event{
   position: fixed; //doensn't have to do anything with the problem
   font-size: 8px; //idem
   width: 50px;
   line-height: 1em;
   overflow: hidden;
}

假设 div 可以显示此文本:

这也是

的很多文字 这个 div,但是

如何在 'but' 后添加 3 个点?

您应该添加这两个条件。您可以在 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>

line-clamp 属性 在特定行数处截断文本。 Read more about line-clamp。 另外:请检查浏览器支持

 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;
}

我制作了一个名为 hideOverflow 的 javascript 函数,它会自动隐藏溢出并用省略号替换它。

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) + '&hellip;';
      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>

目前不支持边距或填充,但您可以轻松调整 hideOverflow 函数的 Calculate lineHeight and maxLineCount for parent's height 部分,以通过填充和边距实现相同的结果。

希望对您有所帮助!