Angular 判断文字是否溢出,超出两行末尾加省略号,hover显示提示文本
需求一:判断文字是否溢出,超出两行末尾加省略号,hover显示提示文本
需求说明
将标签按首字母排序列出,标签内容超出两行时末尾显示省略号,鼠标滑过时判断文本是否溢出,溢出显示提示文本,未溢出则不显示。
思路
鼠标滑过的时候使用(mouseenter) 事件,判断文本的实际高度:scrollHeight 和文本的可视高度 clientHeight ,溢出则设置tips可以显示。以下为具体代码
Html:
<div
class="content-box"
*ngFor="let item of data[letter]"
(mouseenter)="showTip($event)"
>
<span> {{ item.processName | translate }}</span>
<div class="content-box-tit" *ngIf="showTip">{{ item.processName | translate }}</div>
</div>
设置文本超出两行时,末尾显示省略号
.content-box {
position: relative;
display: flex;
width: 19.1%;
height: 75px;
margin: 8px 1.11% 16px 0;
border-radius: 5px;
background-color: #ffffff0d;
color: #ffffffcc;
justify-content: center;
flex-direction: column;
span {
position: absolute;
width: 100%;
padding: 0 16px;
top: 50%;
transform: translateY(-50%);
font: 20px/25px 'Microsoft JhengHei';
text-align: center;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
&:hover {
background-color: rgba(#fff, 0.15);
}
.content-box-tit {
display: none;
position: absolute;
top: 49px;
left: 76%;
width: 127px;
padding: 4px 8px;
border: 1px solid #ffffff33;
border-radius: 4px;
background-color: #000000b3;
font: 14px/20px 'Microsoft JhengHei';
color: #ffffff;
overflow: auto;
}
&:hover .content-box-tit {
display: block;
}
}
TypeScript
showTip(event) {
const scrollHeight = event.target.firstElementChild.scrollHeight;
const clientHeight= event.target.firstElementChild.clientHeight;
this.showTip = scrollHeight > clientHeight + 1;
}
需求二:判断文字是否溢出,超出两行末尾加“展开全部”按钮,点击按钮展开全部信息
需求说明
判断文字是否溢出,超出两行末尾加“展开全部”按钮,点击按钮展开全部信息,点击“显示最少”按钮收起,内容不溢出不显示按钮
思路
与上一个需求判断方式一样
Html:
<div class="navigation" [ngClass]="{ 'show-all': showExpansion }">
<div class="navigation-tit">{{ 'Process List' | translate }}</div>
<div class="navigation-content">
<div class="navigation-inside-content" #navigationElement>
<span
*ngFor="let item of allFlow"
>{{ item.processName | translate }}
</span>
</div>
<span class="navigation-expansion" (click)="showExpansion = !showExpansion" *ngIf="showExpansionBtn">
<ng-container *ngIf="!showExpansion; else isShowExpansion">
{{ '展開全部' | translate }}
</ng-container>
<ng-template #isShowExpansion>
{{ '顯示最少' | translate }}
</ng-template>
</span>
</div>
</div>
设置文本超出两行时,末尾显示省略号
.navigation {
display: flex;
width: 100%;
max-height: 88px;
margin: 12px 0;
transition: all 0.5s ease;
// 展开
&.show-all {
max-height: 100%;
transition: all 1s ease;
}
}
TypeScript
showExpansionBtn = false;
showExpansion = false;
@ViewChild('navigationElement') navigationElement: ElementRef;
ngAfterViewInit(): void {
setTimeout(() => {
this.onResize();
}, 500);
fromEvent(window, 'resize', { capture: true, passive: true })
.pipe(debounceTime(100))
.subscribe((event: Event) => this.onResize());
}
onResize() {
const navigationElement = this.navigationElement.nativeElement;
this.showExpansionBtn = navigationElement.clientHeight < navigationElement.scrollHeight;
}
|