从textNode获取固定的(用省略号表示)textContent [英] Get clamped (with ellipsis) textContent from textNode
问题描述
如何从javascript的节点中获取受限制的文本?参见下面的代码:
console.log(document.getElementById("text1").textContent);
// prints "This is a long text"
console.log(document.getElementById("text2").textContent);
// prints "This is a long text as well"
// expected "This is a long text a..."
.longtext {
width: 140px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
<div id="text1">This is a long text</div>
<div class="longtext" id="text2">This is a long text as well</div>
我想从ID为text2
的元素中获得预期的"This is a long text a..."
.
我发现了类似的问题: http://www.ruzee.com/blog/2007/08/ellipsis-or-truncate-with-dots-via-javascript
How can I get the clamped text from a node in javascript? See below code:
console.log(document.getElementById("text1").textContent);
// prints "This is a long text"
console.log(document.getElementById("text2").textContent);
// prints "This is a long text as well"
// expected "This is a long text a..."
.longtext {
width: 140px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
<div id="text1">This is a long text</div>
<div class="longtext" id="text2">This is a long text as well</div>
I want to get the expected "This is a long text a..."
from the element with id text2
.
I found similar question: How can I access the actual text that is displayed in a DIV when using CSS style overflow: hidden?
In short:
There's no easy way to do it. You have to calculate how much text can be visible in the DIV based on div size, font size, font type and text offset inside div
How to do ellipsis by js http://www.ruzee.com/blog/2007/08/ellipsis-or-truncate-with-dots-via-javascript
这篇关于从textNode获取固定的(用省略号表示)textContent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!