【问题标题】:How to limit the length of text in a paragraph [duplicate]如何限制段落中文本的长度[重复]
【发布时间】:2014-01-30 03:29:52
【问题描述】:

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

打破印度:西方对德拉威和 达利特断层线是 Rajiv Malhotra 写的一本书 Aravindan Neelakandan 认为印度的 完整性正在被破坏。

我希望它显示为:

打破印度:西方对德拉威和 Dalit Faultlines 是 Rajiv Malhotra 写的一本书……

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

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

【问题讨论】:

  • 请显示一些代码?
  • @tewathia - 我希望它默认修剪为一些文本长度。不需要单击按钮。如何做到这一点?
  • 按钮点击只是为了演示,你可以通过在页面加载时运行btn.onclick函数代码自动修剪文本长度,para.innerText = para.innerText.substr(0, 100) + '...';

标签: css html


【解决方案1】:

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

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

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

如果你会使用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);

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

【讨论】:

  • 只想在 css 和 html 中做,但在多行中遇到困难,因此决定使用上面的 javascript 代码。
  • 如果你想限制只使用字符 p { max-width: 250ch; }
猜你喜欢
  • 2018-11-30
  • 2014-04-30
  • 2021-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 2017-12-08
相关资源
最近更新 更多