最近项目中遇到一个场景,搜索页面搜索历史记录超过两行要折叠,同时可以展开显示所有的历史记录。
实现方法:判断每个标签的offsetLeft,每行的offsetLeft相同,依据这个判断当前有多少行。
代码
html代码
<div class="search-new-history-content">
<div class="search-new-history-content-top" :class="[textToggle ? '' : 'active']" ref="historyRef">
<span v-for="(item,index) in historyTag" :key="index" ref="tagRef" @click="clickTag(item)"
:class="[item.title === '展开' || item.title === '收起'? 'chu' : '']">
{{ item.title }}
<img v-if="item.title === '展开'" src="/static/bytx/subject/more_down.svg" alt="">
<img v-if="item.title === '收起'" src="/static/bytx/subject/more_up.svg" alt="">
</span>
</div>
</div>
css
&-content{
position: relative;
padding-left: 20px;
padding-right: 20px;
&-top{
margin-top: 16px;
span{
display: inline-block;
padding: 8px 12px 10px 8px;
border-radius: 6px;
margin-right: 12px;
word-break: keep-all;
background: #F5F6F7;
font-size: 14px;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: #282828;
line-height: 20px;
}
.chu{
display: inline-block;
font-size: 13px;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: #9D9D9D;
background: transparent;
padding: 0;
vertical-align: middle;
img{
transform: translateY(2px);
}
}
}
.active{
height: auto;
overflow: visible;
}
}
js
this.historyTag = [{id: 0, title: '血液病'},{id: 7, title: '血液病有哪几种'},
{id: 3, title: '儿童淋巴瘤'}, {id: 4, title: '喉咙痛声音嘶哑'}, {id: 5, title: '咽喉癌的早期症状'},
{id: 6, title: '成人淋巴癌'},{id: 1, title: '肺癌'},{id: 2, title: '白血病'}
]
// 首先调用默认收起的方法
this.defaultClose()
// 历史搜索默认收起
defaultClose() {
this.$nextTick(() => {
if (!this.historyTag || !this.historyTag.length) {
return
}
let offsetLeft = 0;
this.line = 0
let tags = this.$refs.tagRef
tags.forEach((item,index) => {
if (index === 0) {
this.line = 1
offsetLeft = item.offsetLeft
} else if (item.offsetLeft === offsetLeft) {
// 如果某个标签的offsetLeft和第一个标签的offsetLeft相等 说明增加了一行
this.line++
}
if (this.line > 1) {
// 从第2行开始 设置marginTop
item.style.marginTop = 12 + 'px'
}
if (this.line > 2) {
//从第3行开始 隐藏标签
item.style.display = 'none'
// 显示展开按钮 class名chu是在前面动态添加的
if (item.className === 'chu') {
item.style.display = 'inline-block'
item.style.marginTop = 0 + 'px'
}
}
})
if (this.line > 2) {
// 超过2行 手动添加“展开”按钮
this.historyTag.push({id:0, title: '展开'})
}
let index = this.historyTag.findIndex((item) => {
return item.title === '收起'
})
// 折叠状态 删除“收起”按钮
if (index > -1) {
this.historyTag.splice(index, 1)
}
})
},
// 历史搜索展开
openAll() {
let tags = this.$refs.tagRef
let index = this.historyTag.findIndex((item) => {
return item.title === '展开'
})
// 展开状态 删除“展开”按钮
this.historyTag.splice(index, 1, )
// 添加“收起”按钮
this.historyTag.splice(tags.length - 1, 0, {id:0, title: '收起'})
// 将所有的标签都显示
tags.forEach((item,index) => {
item.style.display = 'inline-block'
})
}
// 点击某个历史搜索
clickTag(item) {
if (item.title === '展开') {
this.openAll()
} else if (item.title === '收起') {
this.defaultClose()
} else {
}
}
实现效果