多行文本收起/展开功能
参考文档
https://juejin.cn/post/6963904955262435336
http://www.webkaka.com/tutorial/html/2021/0624113/
1. 效果图(默认设置超过2行才显示 按钮)
- 文字未超过两行
- 超过两行
2. 优点缺点
1.按钮和文字是环绕型,不会遮挡文字,文字避开会换行,不会像用定位做的,不会遮挡刚刚顶满最后一行的文字,定位的按钮和部分文字出现遮挡
2. 默认超过两行出现 收起、展开功能;可以修改-webkit-line-clamp: 2;改变行数
3.兼容性问题:IE浏览器、火狐、Safari不能生效
3. 代码
<template>
<!-- 按钮和文字是环绕型,不会遮挡文字,文字避开会换行 -->
<!-- 默认超过两行出现 收起、展开功能 -->
<!-- 兼容性问题:IE浏览器不能生效 -->
<div class="wrapper">
<div ref="textarea" :class="btnStatus?'':'textarea'">
<!-- 按钮必须写在文字前面,因为float的原因 -->
<div v-if="btnShow" class="btnChange">
<div @click="changeBtnStatus">{{btnStatus?'收起':'展开'}}</div>
</div>
{{contentWords}}
</div>
</div>
</template>
<script>
export default {
props:{
contentWords:{
type:String,
required:true
}
},
data(){
return{
btnShow:true,
btnStatus:false,
}
},
methods:{
changeBtnStatus(){
this.btnStatus=!this.btnStatus
},
isBtnShow(){
//判断内容高度和视口高度
if(this.$refs.textarea.scrollHeight==this.$refs.textarea.clientHeight){
this.btnShow=false
}
}
},
mounted(){
this.isBtnShow()
}
}
</script>
<style lang="less" scoped>
div.wrapper{
width: 100%;
display: flex;
>div{
text-align:justify;
line-height: 2em;
}
div.textarea{
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
div.btnChange{
color: #2e90ff;
float: right;
height:100%;
display:flex;
align-items:flex-end;
shape-outside:inset(calc(100% - 16px) 0 0);
>div{
cursor: pointer;
}
}
}
</style>
最终版 :兼容谷歌、火狐、edge
<template>
<!-- 按钮和文字是环绕型,不会遮挡文字,文字避开会换行 -->
<div class="wrapper">
<div ref="textarea" :class="btnStatus?'':'textarea'">
<!-- 按钮必须写在文字前面,因为float的原因 -->
<div v-if="btnShow" class="btnChange">
<div :class="btnStatus?'':'btn'" @click="changeBtnStatus">{{btnStatus?'收起':'展开'}}</div>
</div>
{{contentWords}}
</div>
</div>
</template>
<script>
export default {
props:{
contentWords:{
type:String,
required:true
}
},
data(){
return{
btnShow:true,
btnStatus:false,
}
},
methods:{
changeBtnStatus(){
this.btnStatus=!this.btnStatus
},
isBtnShow(){
//判断内容高度和视口高度
if(this.$refs.textarea.scrollHeight==this.$refs.textarea.clientHeight){
this.btnShow=false
}
}
},
mounted(){
this.isBtnShow()
}
}
</script>
<style lang="less" scoped>
div.wrapper{
width: 100%;
display: flex;
font-size: 12px;
>div{
text-align:justify;
line-height: 2em;
}
>div::before {
content: '';
float: right;
height: 100%;
// 重点 这个margin-bottom是btn按钮的高度
margin-bottom: -24px;
}
div.textarea{
overflow: hidden;
max-height: 4em;
}
div.btnChange{
color: #2e90ff;
float: right;
clear: both;
display:flex;
align-items:flex-end;
>div{
cursor: pointer;
margin-left: 20px;
position: relative;
}
.btn::before{
position: absolute;
left: -20px;
width: 20px;
content: '···';
text-align: center;
color: #000;
}
}
}
</style>