【问题标题】:How to limit characters in paragraph?如何限制段落中的字符?
【发布时间】:2020-05-27 10:45:18
【问题描述】:

我有一个角度应用程序,我想限制段落中的字符(p)。 这样它就会在说 50 个字符后返回。

所以我有这个模板:

<section class="echeq-element-html-display border-box"
    [ngClass]="{isYoutubeVideo: isYoutubeVideo}"
    [innerHTML]="doHtmlDisplay(echeqElement)"
></section>

ts:

@Component({
  selector: 'app-html-display',
  templateUrl: './html-display.component.html',
  styleUrls: ['./html-display.component.css']
})

doHtmlDisplay(eCheqElement: EcheqElement): SafeHtml {
  return this.returnSafeHtml(this.getHtml(eCheqElement));
}

这是我的 CSS:

p {
  text-decoration: underline;
  text-overflow: ellipsis; /* will make [...] at the end */
  width: 50px; /* change to your preferences */
  white-space: nowrap; /* paragraph to one line */
  overflow: hidden; /* older browsers */
}

但这不起作用。

那么我必须改变什么?

谢谢

还有一个main.css:

p {
  margin: 0 0 0.75em;
}

当然,我只是想获得该组件的最大字符数,而不是在整个应用程序中。

在 ts 脚本中,我现在是这样的:

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

    if (truncated.length > maxLength) {
      truncated = truncated.substr(0, maxLength) + '...';
    }
    return truncated;
  }

在模板中:


<section  class="echeq-element-html-display border-box" (input)="truncateText('p', 10)" [ngClass]="{isYoutubeVideo: isYoutubeVideo}" [innerHTML]="doHtmlDisplay(echeqElement)"></section>

但没有任何改变。

【问题讨论】:

  • 能给个echeqElement示例内容吗?
  • 你不会用纯javascript吧?

标签: javascript html css angular


【解决方案1】:

你的 css 应该可以工作,在浏览器开发工具中检查 white-space 的值

您也可以尝试在 typescript 中执行此操作

document.querySelector('p').innerText = truncateText('p', 50);

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

    if (truncated.length > maxLength) {
        truncated = truncated.substr(0,maxLength) + '...';
    }
    return truncated;
}

【讨论】:

  • 谢谢。但我正在使用角度。我该如何使用它: document.querySelector('p').innerText = truncateText('p', 50);
  • 当你检测到 p 的变化时使用它,即当用户开始写作时
  • 我的意思是 ts 脚本在哪里?
  • 顺便说一句,它是一个只读输入字段。它来自一个 tinymce 输入字段
  • 然后当您将文本渲染到此输入字段时,将其应用到那里
【解决方案2】:

像下面这样使用

doHtmlDisplay(text, limit = 50) {
 if (text.length > limit) {
  text = text.substring(0, limit);
 } else {
  text;
 }
 return text;
}

在你的 HTML 中

<section class="echeq-element-html-display border-box"
[ngClass]="{isYoutubeVideo: isYoutubeVideo}"
[innerHTML]="doHtmlDisplay(echeqElement, 100) | safeHtml"></section>

使用safeHtml 管道

【讨论】:

  • 您可以使用切片角管 {{youText |切片:0:20 }}
  • 当我们将 slice 与 [innterHTML] 一起使用时会出错
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多