kab*_*oya 4 javascript css hidden overflow
在javscript 中,我创建了一个将文本放入 div 的函数。然而,有时这个文本对于这个 div 来说太长了。所以在css中我将溢出设置为隐藏。
overflow: hidden
Run Code Online (Sandbox Code Playgroud)
我不仅不想显示此溢出,还想将其替换为“...”,以便用户看到信息不完整。
我已经尝试计算字符串的长度,并在几个字符后停止它,但由于我的 div 非常窄,它似乎是一个很好的解决方案。
我怎么能这样做?
编辑:我想要多行,而不是一条
HTML:
<div id="event">This is way too much text for this div, but i want to show it partly</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
#event{
position: fixed; //doensn't have to do anything with the problem
font-size: 8px; //idem
width: 50px;
line-height: 1em;
overflow: hidden;
}
Run Code Online (Sandbox Code Playgroud)
假设 div 可以显示此文本:
这个 div 的
文字太多了
,但是
如何在“但是”后添加 3 个点?
该line-clamp属性在特定行数处截断文本。
阅读有关 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;
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个名为 的 JavaScript 函数hideOverflow,它会自动隐藏溢出并用省略号替换它。
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'));Run Code Online (Sandbox Code Playgroud)
div {
width: 300px;
height: 100px;
font-size: 18px;
border: 1px black solid;
}
p {
margin: 0px;
padding: 0px;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
当前不支持边距或填充,但您可以轻松调整函数Calculate lineHeight and maxLineCount for parent's height的部分hideOverflow,以便通过填充和边距实现相同的结果。
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
891 次 |
| 最近记录: |