将隐藏的溢出替换为"..."



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来说
,这是太多的文字,但是

如何在"但是"后添加 3 个点?

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部分,以便使用填充和边距实现相同的结果。

希望这有帮助!

p {     
display: inline-block;
text-overflow: ellipsis;
line-height: 1.6rem;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 4; //it shows how many rows will display
-webkit-box-orient: vertical;
max-height: 7.2rem;
}

您应该添加这两个条件。您可以在小提琴中查看演示。

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>

最新更新