vue3 折叠内容时,页面自动滚动到当前 item 的内容位置

对于在折叠时,页面能够自动滚动到原来 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 的调整值是为了留出一些空白,可以根据需要进行调整。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值