javascript - 如何检查 td 中文本的行长并在单击时显示更多内容

标签 javascript html css angular

我正在尝试显示 “查看更多”,当 单击 时,它将显示 td 中的完整内容。 see more的条件是当td里面的文字超过3行时出现,然后显示“see more”和onclick展开并显示完整内容。

这里,宽度设置为 318px,用户可以更改也可以不更改。

我可以将 td 的行高设置为 21px,并且根据计算我可以计算行数,但在数组中文本是随机的并且数组大小随着滚动而增加。数组大小可能在 1000s 或更多。因此,我不想维护具有 1000 个或更多元素的数组大小,这些元素包含有关行数的每个文本(数组元素)的状态。

有没有更好的方法可以将一个简单的技巧应用于所有文本(数组元素)。

这是 stackblitz 链接:- https://stackblitz.com/edit/angular7-test-mndgc5?file=app%2Fapp.component.html

.ts

// textss is dyanamic and can be 100 or with a scroll

textsss = [
"In 2005, Nature published a peer review comparing 42 science articles from Encyclopædia Britannica and Wikipedia and found that Wikipedia's level of accuracy approached that of Britannica. Time magazine stated that the open-door policy of allowing anyone to edit had made Wikipedia the biggest and possibly the best encyclopedia in the world, and was a testament to the vision of Jimmy Wales.",
 "005, Nature published a peer review comparing 42 science articles from Encyclopædia Britannica and Wikipedia and found that Wikipedia's level of accuracy approached that of Britannica.",
"abcdffff",
"ished a peer review comparing 42 science articles from Encyclopædia Britannica and Wiki",
.
.
.
.
]

 ngAfterViewInit(){
  this.viewHeight = this.elementView.nativeElement.offsetHeight;
     console.log( this.viewHeight);
    this.lines = Math.round(this.viewHeight/ 21);
     console.log(this.lines);
     if(this.lines > 3){
       this.dynamicTextHeight = 3 * 21;
     }
  }

  expand(){
     this.dynamicTextHeight = this.lines * 21;
  }

.html

<table class="table">
<tbody >
<tr *ngFor="let text of textsss;let i = index;" [style.height.px]="dynamicTextHeight">
<td #mainScreen>{{i + 1}}. <span *ngIf="lines > 3" (click)="expand()">... see more</span>{{text}}</td>
</tr>
</tbody>
</table>

最佳答案

更新:

由于 CSS 不够,我重构了将每个框作为一个组件来处理,并在开始时(AfterViewInit)进行了高度计算,并使用它来显示或不显示额外的行。

演示:https://stackblitz.com/edit/angular7-test-x7pqvp


您可以通过 CSS + 切换 ngStyle 来实现:

  1. text-overflow + 固定高度(根据font-sizeline-height 和要显示的行数计算)。 SASS 可以帮助进行该计算。
  2. 通过切换 ngStyle 定义显示更多/更少。

关于javascript - 如何检查 td 中文本的行长并在单击时显示更多内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54608850/

相关文章:

javascript - 用单引号设置 angurlarjs 属性

javascript - 正在加载文件名中包含今天日期的 XML 文件...如果不存在具有今天日期的文件,则需要回退到旧文件

javascript - IE 和 Chrome 上的 MooTools 问题

javascript - HTML5 Canvas 上的外部字体

javascript - 文本阻碍文本区域

javascript - 预加载背景图片

Javascript 图像翻转

html - 在 Sencha Touch 中为不同的移动设备分辨率创建启动画面

javascript - 如何在矩形的底部svg JS中绘制圆 Angular

html - Bootstrap 3 中产生过多的空格