对于在折叠时,页面能够自动滚动到原来 item 的位置,需要更多的逻辑和处理。这是一个稍微复杂一点的需求,需要动态计算滚动位置。以下是一个示例,展示如何在 Vue 中实现这一功能:
<template>
<div>
<div v-for="item in items" :key="item.id">
<div
:ref="`content-${item.id}`"
:class="{ 'collapsed-content': !item.isExpanded }"
>
{{ item.content }}
</div>
<button @click="toggleContent(item)">
{{ item.isExpanded ? 'Show less' : 'Show more' }}
</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{
id: 1,
content: 'Your very long text for item 1 goes here...',
isExpanded: false,
},
{
id: 2,
content: 'Your very long text for item 2 goes here...',
isExpanded: false,
},
// ... other items
],
};
},
methods: {
toggleContent(item) {
if (item.isExpanded) {
this.scrollToItem(item);
}
item.isExpanded = !item.isExpanded;
},
scrollToItem(item) {
const refName = `content-${item.id}`;
const element = this.$refs[refName][0];
if (element) {
const rect = element.getBoundingClientRect();
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const targetScroll = scrollTop + rect.top - 20; // -20 是为了留出一些空白
window.scrollTo({ top: targetScroll, behavior: 'smooth' });
}
},
},
};
</script>
<style>
.collapsed-content {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>
在上述示例中,我们首先在折叠时调用 scrollToItem
方法,该方法会滚动到当前 item 的位置。在滚动时,我们使用 getBoundingClientRect
来获取元素的位置信息,并使用 window.scrollTo
将页面滚动到该位置。
这个方法可以确保在折叠时,页面自动滚动到原来 item 的位置。需要注意的是,-20
的调整值是为了留出一些空白,可以根据需要进行调整。