从textNode获取固定的(用省略号表示)textContent [英] Get clamped (with ellipsis) textContent from textNode

查看:89
本文介绍了从textNode获取固定的(用省略号表示)textContent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆