我创建了一个类似论坛的页面,其中所有消息如下(简化):
<div class="message-wrapper" *ngFor="let node of allNodes">
<div [class]="isExpanded(node.id) ? 'message-content expanded' : 'message-content'">
<div class="content" [innerHtml]="node.comment"></div>
<span (click)="toggleExpand(node.id)" class="showMore">{{ isExpanded(node.id) ? 'Show less' : 'Show more' }}</span>
</div>
</div>
还有CSS
.message-content {
overflow-y: hidden;
.content {
line-height: 1.5vh;
max-height: 6vh;
overflow-y: hidden;
}
}
.message-content.expanded {
max-height: 10000000vh;
overflow: visible !important;
.content {
overflow: visible;
max-height: 100000000vh;
}
}
当单击“显示更多”和“显示更少”范围时,div.content
会按预期展开。
我目前遇到的问题是,我只想在文本实际溢出时才显示“显示更多”。
我知道我可以通过减去 scrollHeight
和 innerHeight
来找到它,但是为了让它工作,我需要有正确的(唯一的)nativeElement
在我的 Controller 中相应的 div.comment
。
所以我的问题是:
当 div.content
溢出而页面上的所有消息都具有相同的类等时,如何显示“显示更多”范围?
使这个问题与现有问题不同的是,我没有单个元素,但我有多个相同的元素(多条消息),因此需要唯一的节点元素。
最佳答案
创建了一个解决方法,我将动态 ID 添加到所有 div 和 span。然后我遍历所有节点并检查文本是否溢出。如果是,我将 hidden=false
设置为标签。
for(let comment of this.allComments) {
//element which contains the comment content
let content = document.getElementById('div'+comment.id);
// if the element height is bigger than the displayed height (with an error margin of 10)
if(content.scrollHeight - content.clientHeight > 10) {
// the corresponding 'show more' label
let label = document.getElementById('label'+comment.id);
label.hidden = false;
}
}
关于html - 动态显示 "show more",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51419567/