在 Angular 应用程序的标题部分使用 CSS 或 JS 实现可点击展开的文本

问题描述 投票:0回答:2

我的 Angular 应用程序的主页上有一个部分,我在其中显示一些带有标题和两行开头内容的故事。我想做的是在开头两行的末尾提供一个“展开”按钮,单击该按钮后,文本空间将展开以容纳文本的其余部分。我还希望它可以切换,以便可以通过单击同一按钮再次最小化文本。

有没有一种方法可以单独使用 CSS/HTML 来完成此任务?或者这最好通过 JavaScript 完成——或者两者的组合?我还想知道 Angular 材料是否有现成的东西来完成这种 UI 处理。也许扩展面板(https://material.angular.io/components/expansion/overview)可以工作? Google 在 Google 新闻 (https://news.google.com) 中使用什么来制作自己的可点击展开的故事?

总的来说,我正在寻找一种优雅、简单且适用于现代浏览器的解决方案。另请注意,这将是动态内容,因此它需要能够通过计算字符数或类似的内容来工作,而不是提前将信息分组到不同的 div 元素中。

javascript css angular angular-material expand
2个回答
3
投票

由于您使用的是 Angular,因此您应该以“角度”方式执行此操作。

我们将使用 CSSAngular Animations

工作示例


说明:

我们的组件将被称为

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()
函数,以及根据
@panelState
属性绑定 card-body 当前状态的
folded

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 { }

0
投票

我喜欢上面的解决方案,但是当我们尝试对对象数组使用扩展时,所有消息都会同时扩展。我有时需要一个。任何想法都将受到高度赞赏。

© www.soinside.com 2019 - 2024. All rights reserved.