likes
comments
collection
share

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

作者站长头像
站长
· 阅读数 5

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

完成效果:

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

实现思路:

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

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

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

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

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

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

完整示例代码如下

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


 .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

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


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