Html 如何限制段落中的文本长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21447269/
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-08-29 00:45:38  来源:igfitidea点击:

How to limit the length of text in a paragraph

csshtml

提问by user3193385

I have a paragraph as below, which may be of any length:

我有一段如下,可以是任意长度:

Breaking India: Western Interventions in Dravidian and Dalit Faultlines is a book written by Rajiv Malhotra and Aravindan Neelakandan which argues that India's integrity is being undermined.

Breaking India: Western Interventions in Dravidian and Dalit Faultlines 是 Rajiv Malhotra 和 Aravindan Neelakandan 写的一本书,认为印度的完整性正在受到破坏。

I want it to appear as:

我希望它显示为:

Breaking India: Western Interventions in Dravidian and Dalit Faultlines is a book written by Rajiv Malhotra...

打破印度:西方干预德拉威和达利特断层线是拉吉夫·马尔霍特拉 (Rajiv Malhotra) 撰写的一本书...

below is the code which populates description in my website:

下面是在我的网站中填充描述的代码:

currently description goes to any no. of line based on product, i need to limit this to 3 lines.

目前描述去任何没有。基于产品的行数,我需要将其限制为 3 行。

回答by Josh

If you want to use html and css only, your best bet would probably be to use something like:

如果你只想使用 html 和 css,你最好的选择可能是使用类似的东西:

p {
     width: 250px;
     white-space: nowrap;
     overflow: hidden;
     text-overflow: ellipsis;
}

Here is an example: http://jsfiddle.net/nchW8/source: http://css-tricks.com/snippets/css/truncate-string-with-ellipsis/

这是一个例子:http: //jsfiddle.net/nchW8/来源:http: //css-tricks.com/snippets/css/truncate-string-with-ellipsis/

If you can use javascript you can use this function:

如果您可以使用javascript,则可以使用此功能:

function truncateText(selector, maxLength) {
    var element = document.querySelector(selector),
        truncated = element.innerText;

    if (truncated.length > maxLength) {
        truncated = truncated.substr(0,maxLength) + '...';
    }
    return truncated;
}
//You can then call the function with something like what i have below.
document.querySelector('p').innerText = truncateText('p', 107);

Here is an example: http://jsfiddle.net/sgjGe/1/

这是一个例子:http: //jsfiddle.net/sgjGe/1/