欢迎来到代码驿站!

vue

当前位置:首页 > 网页前端 > vue

Vue实现文本展开收起功能

时间:2023-03-02 09:34:43|栏目:vue|点击:

本文实例为大家分享了Vue实现文本展开收起功能的具体代码,供大家参考,具体内容如下

先说说需求,以及实现的需求

1、移动端H5,发表留言后跳转到评论列表,超过5行文字,多余的需要隐藏,并且需要有展开/收起按钮

2、未超过5行的文字,不需要展示展开收起/按钮

下面直接丢出核心代码

<div :ref="`community_${index}`" 
      class="community-words" 
      :class="{'more-line':item.domHeight > 300 && !item.open}" 
      v-html="contentHtml(item.content)" >
</div>
<span class="toggle-fold" 
      v-show="item.domHeight > 300" 
      @click="toggleFoldFn(item,index)">
      {{ item.open ? '收起' : '展开'}}
 </span>

实现思路:获取数据后先渲染页面,然后计算渲染的dom元素高度,在动态添加class,设置超过的样式,以及显示展开收起按钮,目前是移动端h5,流畅度满足正常需求!下面说说具体细节:

div里面显示的是文字内容,文字的行高我这边固定是60px,所以超过5行的高度就是300px,这里用300判断,这个判断条件,可以根据实际情况修改,open字段是展开收起使用的,默认false,下面看看具体的js代码

 apiQueryCommentsList(data).then((res) => {
   if(res.data && res.data.length){
     this.communityList = res.data;
       this.$nextTick(() => {
          for(let k = 0; k < this.communityList.length; k++){
                const domHeight = this.$refs[`community_${k}`][0].offsetHeight;
                const open = domHeight < 300 ? true : false;
                this.$set(this.communityList[k],'domHeight',domHeight);
                this.$set(this.communityList[k],'open',open);
              }
 
            });
          }else{
            this.communityList = [];
          }
        });

获取数据后先渲染,再获取dom高度,通过$set给每个数据添加domHeight属性,以及open属性,open属性还会被用到展开收起功能,接下来看展开收起功能

toggleFoldFn(item){
        // ios下点击展开需要记录滚动条位置,点击收起的时候回到展开的位置
        if(!item.open){
          this.scollTop = document.documentElement.scrollTop || document.body.scrollTop;
        }else{
          const ua = window.navigator.userAgent.toLocaleLowerCase();
          const isIOS = /iphone|ipad|ipod/.test(ua);
          if(this.scollTop !== null && isIOS){
            window.scrollTo(0,this.scollTop);
          }
        }
        item.open = !item.open;
      }

item.open = !item.open; 这句代码就可以实现展开收起功能,其他的代码是为了解决ios端,展开收起后滚动条位置发生改变做的处理,上述代码即可完成展开收起功能!

替换换行符代码:

contentHtml(content){
   return content.replace(/\n/g, "<br/>");
}

下面贴出css代码

.community-words {
    font-size: 32px;
    font-family: PingFang SC;
    font-weight: 400;
    line-height: 60px;
    color: rgba(6, 15, 38, 1);
    word-wrap:break-word;
    word-break:normal;
}
.more-line {
    word-break: break-all;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 5;
    overflow: hidden;
}

上一篇:vue-cli3在main.js中console.log()会报错的解决

栏    目:vue

下一篇:vue项目ElementUI组件中el-upload组件与图片裁剪功能组件结合使用详解

本文标题:Vue实现文本展开收起功能

本文地址:http://www.codeinn.net/misctech/226732.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有