Vue實現(xiàn)文本展開收起功能
本文實例為大家分享了Vue實現(xiàn)文本展開收起功能的具體代碼,供大家參考,具體內(nèi)容如下
先說說需求,以及實現(xiàn)的需求
1、移動端H5,發(fā)表留言后跳轉到評論列表,超過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>實現(xiàn)思路:獲取數(shù)據(jù)后先渲染頁面,然后計算渲染的dom元素高度,在動態(tài)添加class,設置超過的樣式,以及顯示展開收起按鈕,目前是移動端h5,流暢度滿足正常需求!下面說說具體細節(jié):
div里面顯示的是文字內(nèi)容,文字的行高我這邊固定是60px,所以超過5行的高度就是300px,這里用300判斷,這個判斷條件,可以根據(jù)實際情況修改,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 = [];
? ? ? ? ? }
? ? ? ? });獲取數(shù)據(jù)后先渲染,再獲取dom高度,通過$set給每個數(shù)據(jù)添加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; 這句代碼就可以實現(xiàn)展開收起功能,其他的代碼是為了解決ios端,展開收起后滾動條位置發(fā)生改變做的處理,上述代碼即可完成展開收起功能!
替換換行符代碼:
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;
}以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
在vue中獲取微信支付code及code被占用問題的解決方法
這篇文章主要介紹了在vue中獲取微信支付code及code被占用問題的解決方法。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04
vue?beforeDestroy?clearInterval清除定時器失效的解決
這篇文章主要介紹了vue?beforeDestroy?clearInterval清除定時器失效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06

