2016-04-29 32 views
0

如何从javascript中的节点获取夹紧的文本?请参见下面的代码:从textNode获取夹紧(带省略号)textContent

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>

我想从该元素的预期"This is a long text a..." id为text2

回答

0

做省略号抵消可见然您的代码段,它可以正常工作,如你所料。 'text-overflow:ellipsis'按预期工作。这里是工作代码的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>