Get clamped (with ellipsis) textContent from textNode

杀马特。学长 韩版系。学妹 提交于 2019-12-02 12:34:42

问题


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.


回答1:


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




回答2:


Ran your code snippet, it works fine as you expected. 'text-overflow: ellipsis' works as expected. Here is JSFiddle link for working code https://jsfiddle.net/qx5mL548/

Didn't understand what kind of problem you are getting. You can try this code n let me know if it works:

<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>


来源:https://stackoverflow.com/questions/36936263/get-clamped-with-ellipsis-textcontent-from-textnode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!