我的Angular应用程序主页上有一个部分,我在其中显示一些故事,标题和大约两行开场白内容。我想做的是在开头两行的末尾提供一个"扩展"按钮,当单击该按钮时,将导致文本空间扩展,以容纳剩余的文本。我还希望它可以切换,这样点击同一个按钮可以再次最小化文本。
有没有一种方法可以让我单独使用CSS/HTML来实现这一点?或者这最好通过JavaScript完成——或者两者结合?我还想知道Angular材质是否有一些开箱即用的东西来完成这种UI处理。也许是一个扩展面板(https://material.angular.io/components/expansion/overview)可以工作吗?谷歌在谷歌新闻中使用哪些可点击扩展的故事(https://news.google.com)?
总的来说,我正在寻找一个优雅、简单、适用于现代浏览器的解决方案。此外,请注意,这将是动态内容,因此它需要能够通过计算字符数或类似的方法来工作,而不是提前将信息分组到不同的div元素中。
由于您使用的是Angular,因此应该以"Angular"的方式进行操作。
我们将使用CSS和角度动画。
工作示例
说明:
我们的组件将被称为app-card
,通过点击其标题,我们将显示/隐藏卡"主体"的全部内容。
card.component.html
<div class="card-container">
<div class="card-header" (click)="toggleFold()">
I am the head of the card
</div>
<div class="card-body" [@panelState]="folded">
<ng-content></ng-content>
</div>
</div>
需要注意的关键部分是当我们单击卡片标题时发生的toggleFold()
函数,以及根据folded
属性绑定卡片主体的当前状态的@panelState
。
card.component.ts
import { Component, OnInit } from '@angular/core';
import { animate, state, style, transition, trigger } from '@angular/animations';
@Component({
selector: 'app-card',
templateUrl: './card.component.html',
styleUrls: ['./card.component.css'],
animations : [
// Here we are defining what are the states our panel can be in
// and the style each state corresponds to.
trigger('panelState', [
state('closed', style({ height: '32px', overflow: 'hidden' })),
state('open', style({ height: '*' })),
transition('closed <=> open', animate('300ms ease-in-out')),
]),
],
})
export class CardComponent {
folded = 'closed';
// toggleFold function simply changes our folded property
// between "open" and "closed"
toggleFold(){
this.folded = this.folded === 'open' ? 'closed' : 'open';
}
}
注意:
- 为了使用角度动画,您需要将"@angular/platform browser/animations">中的"BrowserAnimationsModule">导入
app.module.ts
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { CardComponent } from './card/card.component';
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule, // <<
],
declarations: [
AppComponent,
CardComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule { }