01CSS 实现多行文本“展开收起”

最近在开发移动端的评论内容功能时,我遇到了一个需求,需要实现一个展开收起效果。主要目的是让用户能够方便地查看和隐藏评论内容,现在想将我的成果分享给大家

完成效果:

实现思路:

1.准备一个文本的外部容器( content),并将最大高度设置为65px(根据实际需求而定),超出内容设置不可见

2.文本容器的高度(text-content)不做样式设置,这个容器是为了获取内容实际高度

3.通过 js 获取文本容器的高度(text-content),判断文本高度是否超过外部容器(content)的最大高度,控制展开收起按钮是否显示

4.点击按钮时根据条件设置容器(content)的最大高度,css 对通过 transition 对 max-height 设置过渡效果

完整示例代码如下

HTML

html 复制代码
 <div class="container">
     <div class="content">
         <div class="text-content">
                1月30日上午10时,中国贸促会将召开1月例行新闻发布会,介绍第二届链博会筹备进展情况;
                2025大阪世博会中国馆筹备进展;2023年全国贸促系统商事认证数据;2023年贸法通运行情况;
                2023年11月全球经贸摩擦指数;2023年12月全球知识产权保护指数月度观察报告;助力培育外贸新动能有关工作考虑等。
         </div>
     </div>
     <button class="btn">展开</button>
 </div>

CSS

css 复制代码
 .container {
	width: 260px;
	padding: 20px;
	border: 1px solid #ccc;
	margin: 50px auto;
 }

 .content {
	max-height: 65px;
	overflow: hidden;
	transition: max-height 0.5s;
 }


 .btn {
	display: flex;
	width: 40px;
	color: cornflowerblue;
	outline: none;
	border: none;
	background-color: transparent;
 }

JS

js 复制代码
    const maxHeight=65
    const btn = document.querySelector('.btn')
    const content = document.querySelector('.content')
    const textContent=document.querySelector('.text-content')
    const textHeight=textContent.getBoundingClientRect().height // 文本高度
    const contentHeight=content.getBoundingClientRect().height  // 容器高度
    let flag = false
    if (textHeight < maxHeight) {
        btn.style.display = 'none'
    }
    btn.addEventListener('click', () => {
        if (!flag) {
            content.style.maxHeight=textHeight+'px'
            btn.innerHTML = '收起'
            flag = true
        } else {
            content.style.maxHeight=contentHeight+'px'
            btn.innerHTML = '展开'
            flag = false
        }
    })

实现一个功能的方式往往有多种,你们是怎么解决的呢?

相关推荐
木斯佳8 分钟前
前端八股文面经大全:快手电商日常实习前端一面(2026-05-15)·面经深度解析
前端·面试·面经
2601_958492557 小时前
Optimizing Engagement with Freehead Skate - HTML5 Game - Construct 3
前端·html·html5
茉莉玫瑰花茶8 小时前
工作流的常见模式 [ 1 ]
java·服务器·前端
zhangxingchao8 小时前
AI应用开发六:企业知识库
前端·人工智能·后端
山峰哥9 小时前
SQL慢查询调优实战:从全表扫描到索引覆盖的完整复盘
前端·数据库·sql·性能优化
红尘散仙9 小时前
一个 `#[uniffi::export]`,把 Rust 接进 React Native
前端·后端·rust
moshuying9 小时前
AI Coding 最大的 token 黑洞,可能根本不是 prompt
前端
红尘散仙9 小时前
一行 `#[specta::specta]`,让 Tauri IPC 有类型
前端·后端·rust
lichenyang45310 小时前
HarmonyOS HMRouter 接入记录:从普通 Tab Demo 到路由跳转
前端