发布时间:2024-12-05 15:01
一个场景,在搜索记录的时候,搜索记录作为一个tag列表,超过两行的时候要折叠,然后支持展开
1.可以使用容器宽度跟每一个tag的长度去比较,加起来超过一行的时候,行数+1的方法,但是这里是用了容器用了padding 拿不到容器的width值,计算会不准确
2.使用offsetLeft
,每行的第一个的offetLeft值都是一样的,所以用着这个来判断行数
<template>
<div class="history">
<div
ref="contentRef"
class="contentHistory"
>
<van-tag
plain
:closeable="!isDeleteShow"
type="primary"
@close="close"
>999van-tag>
<van-tag
plain
:closeable="!isDeleteShow"
type="primary"
>感冒灵颗粒van-tag>
<van-tag
plain
:closeable="!isDeleteShow"
type="primary"
>感冒灵颗粒van-tag>
<van-tag
plain
:closeable="!isDeleteShow"
type="primary"
>感冒灵颗粒van-tag>
<van-tag
plain
:closeable="!isDeleteShow"
type="primary"
>感冒灵颗粒van-tag>
<van-tag
plain
:closeable="!isDeleteShow"
type="primary"
>感冒灵颗粒van-tag>
<van-tag
plain
:closeable="!isDeleteShow"
type="primary"
>感冒灵颗粒van-tag>
<van-tag
plain
:closeable="!isDeleteShow"
type="primary"
>感冒灵颗粒wwwwwwwwvan-tag>
<van-tag
plain
:closeable="!isDeleteShow"
type="primary"
>999van-tag>
<van-tag
plain
type="primary"
:closeable="!isDeleteShow"
>99999123van-tag>
<van-tag
plain
type="primary"
:closeable="!isDeleteShow"
>99999123van-tag>
<van-tag
plain
type="primary"
id="down"
@click="open"
>
<van-icon name="arrow-down" />
van-tag>
div>
div>
template>
样式
.contentHistory {
display: flex;
flex-wrap: wrap;
padding: px2rem(0) px2rem(40);
// text-align: center;
:deep(.van-tag) {
background-color: #ffffff;
border-radius: px2rem(36);
color: #646566;
font-size: px2rem(30);
padding: px2rem(10) px2rem(10);
margin-left: px2rem(20);
margin-right: px2rem(20);
margin-bottom: px2rem(30);
border: 1px solid #fff;
}
}
<script lang="ts">
const rem2px = ($rem) => {
return ($rem / 10) * 750;
};
import { onMounted, ref } from 'vue';
export default {
setup() {
// 容器ref
const contentRef = ref(null);
let hideIndex = 0; // 不带x的隐藏的标签索引 因为打开再关闭的时候x会影响行数
onMounted(() => {
hide();
});
const hide = (first = true) =>{
let line = 0,
offsetLeft = 0;
const tags = document.querySelectorAll('.contentHistory > .van-tag');
// 计算行数 往后的行数第一个offsetLeft跟第一个标签的offsetLeft一样
tags.forEach((item,index) => {
if(index === 0){
line = 1;
offsetLeft = item?.offsetLeft;
} else if (item?.offsetLeft === offsetLeft) {
line++;
}
if (line === 3 && first) {
// 第3行的时候 最后一个的下标
hideIndex = index - 1;
}
if (line > 2) {
item.style.display = 'none';
if(item.id==='down'){
item.style.display = 'block';
tags[hideIndex].style.display = 'none';
}
}
});
console.log('sss', line);
}
let isDeleteShow = ref(true);
const openAll = () => {
const tags = document.querySelectorAll('.contentHistory > .van-tag');
tags.forEach((item) => {
item.style.display = 'block';
});
};
const open = () => {
console.log('open');
isDeleteShow.value ? openAll() : hide(false);
isDeleteShow.value = !isDeleteShow.value;
};
return {
contentRef,
isDeleteShow,
open,
};
},
};
</script>
重点