从textNode获取(使用省略号)textContent

时间:2016-04-29 10:44:08

标签: javascript html css ellipsis

如何从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>
&#13;
&#13;
&#13;

我希望从ID为"This is a long text a..."的元素中获取预期的text2

2 个答案:

答案 0 :(得分:1)

我发现了类似的问题:How can I access the actual text that is displayed in a DIV when using CSS style overflow: hidden?

简而言之:

  

没有简单的方法可以做到这一点。您必须根据div内的div大小,字体大小,字体类型和文本偏移量计算DIV中可见的文本数量

如何通过js http://www.ruzee.com/blog/2007/08/ellipsis-or-truncate-with-dots-via-javascript

进行省略

答案 1 :(得分:0)

运行您的代码段,它可以正常工作。 &#39;文本溢出:省略号&#39;按预期工作。这是工作代码https://jsfiddle.net/qx5mL548/

的JSFiddle链接

没有理解你遇到了什么样的问题。你可以试试这段代码,让我知道它是否有效:

<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>
相关问题