javascript 省略号截断长文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11093908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:04:40  来源:igfitidea点击:

Ellipsis to truncate a long text

javascripthtmlcss

提问by user1465233

I am using ellipsis concept to truncate a long text in my HTML. I have successfully managed to truncate the sentence but the "..." wont appear in my HTML. I use the following for the css

我正在使用省略号概念来截断 HTML 中的长文本。我已经成功地截断了句子,但“...”不会出现在我的 HTML 中。我对 css 使用以下内容

The output appears to be fine.. i.e., for test test test test test test test test test the out put is test test test when i actually want it as test test test...

输出似乎很好.. 即,对于测试测试测试测试测试测试测试测试,当我真正想要它作为测试测试测试时,输出是测试测试测试...

<div style="text-align:left; line-height: 20px; white-space: nowrap;
            overflow: hidden; text-overflow: ellipsis; width: 99%;
            display : block;"> 

回答by bfavaretto

I'm not sure what you're asking, or what you are seeing, but the text will only be truncated if there's not enough space in the container. For example:

我不确定你在问什么,或者你看到了什么,但只有当容器中没有足够的空间时,文本才会被截断。例如:

<style type="text/css">
div {
    white-space: nowrap; 
    overflow: hidden; 
    text-overflow: ellipsis; 
    width: 100px;
}
</style>
<div> 
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

http://jsfiddle.net/jS7ea/

http://jsfiddle.net/jS7ea/

Here I limited the div's width to 100px, and it displays just this:

在这里,我将 div 的宽度限制为 100px,它显示如下:

Lorem ipsu...

On your example you have 99% width, so you'll only see the truncation if that's less than the actual content width (try resizing the browser window to check).

在您的示例中,您有 99% 的宽度,因此您只会看到小于实际内容宽度的截断(尝试调整浏览器窗口的大小以进行检查)。

回答by Iman

function shorten(text, maxLength) {
    var ret = text;
    if (ret.length > maxLength) {
        ret = ret.substr(0,maxLength-3) + "...";
    }
    return ret;
}

you can also use &hellip; …(Horizontal Ellipsis) instead of 3 dots

您也可以使用 &hellip; …(Horizo​​ntal Ellipsis) 而不是 3 点

source: http://html5hub.com/ellipse-my-text

来源:http: //html5hub.com/ellipse-my-text