如何用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..."
。
我发现了类似的问题:当使用CSS样式溢出时,如何访问div中显示的实际文本:隐藏?
简而言之:
没有简单的方法可以做到这一点。你必须根据DIV大小、字体大小、字体类型和DIV 内的文本偏移量来计算在DIV中可以看到多少文本
如何用js做省略号http://www.ruzee.com/blog/2007/08/ellipsis-or-truncate-with-dots-via-javascript
运行您的代码片段,它可以正常工作。'文本溢出:省略号按预期工作。这里是工作代码的JSFiddle链接https://jsfiddle.net/qx5mL548/
不明白你遇到了什么样的问题。你可以试试这个代码,让我知道它是否有效:
<html>
<head>Ellipsis</head>
<style>
.longtext {
width: 140px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
</style>
<body>
<div id="text1">This is a long text</div>
<div class="longtext" id="text2">This is a long text as well</div>
</body>
</html>