You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt中未知高度元素实现height过渡效果的方法

在Nuxt中实现未知高度元素的高度过渡效果

需求说明

  • 点击按钮,元素高度变为0(收起状态)
  • 再次点击按钮,元素恢复原高度(展开状态)

方案一:通过ref + nextTick获取精确高度实现过渡

这种方案会先获取元素展开时的实际高度,再通过动态绑定height属性配合过渡动画实现精准的展开/收起效果。

<template>
  <div class="collapse-container">
    <button @click="toggleCollapse">切换展开/收起</button>
    <transition name="height-transition">
      <div 
        ref="targetContent" 
        :style="{ height: isCollapsed ? '0' : `${originalHeight}px` }"
        class="target-content"
      >
        <!-- 这里是高度未知的内容,比如动态渲染的文本、列表等 -->
        这是一段高度不确定的内容,可能包含多行文本、图片或其他动态元素。
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'

// 控制收起/展开状态
const isCollapsed = ref(false)
// 绑定目标元素的ref
const targetContent = ref(null)
// 存储元素展开时的实际高度
const originalHeight = ref(0)

onMounted(async () => {
  // 等待DOM渲染完成后获取元素高度
  await nextTick()
  if (targetContent.value) {
    originalHeight.value = targetContent.value.offsetHeight
  }
})

// 切换状态的方法
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}
</script>

<style scoped>
.collapse-container {
  width: 300px;
  margin: 20px;
}

.target-content {
  overflow: hidden;
  transition: height 0.3s ease-in-out;
  padding: 10px;
  border: 1px solid #eee;
}

/* 可选:自定义过渡类的动画细节 */
.height-transition-enter-from,
.height-transition-leave-to {
  height: 0 !important;
  padding: 0 10px !important;
}

.height-transition-leave-from,
.height-transition-enter-to {
  height: var(--original-height) !important;
}
</style>

方案二:动态设置max-height实现过渡

如果不想获取精确高度,可以用max-height来模拟高度变化,实现更简单,但需要预估一个足够大的max-height值(确保大于元素可能的最大高度)。

<template>
  <div class="collapse-container">
    <button @click="toggleCollapse">切换展开/收起</button>
    <div 
      :class="{ 'collapsed': isCollapsed }"
      class="target-content"
    >
      <!-- 高度未知的内容 -->
      这是一段高度不确定的内容,可能包含多行文本、图片或其他动态元素。
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const isCollapsed = ref(false)

const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}
</script>

<style scoped>
.collapse-container {
  width: 300px;
  margin: 20px;
}

.target-content {
  max-height: 1000px; /* 根据内容预估一个足够大的值 */
  overflow: hidden;
  transition: max-height 0.3s ease-in-out;
  padding: 10px;
  border: 1px solid #eee;
}

.target-content.collapsed {
  max-height: 0;
  padding: 0 10px;
}
</style>

方案对比

  • 方案一:过渡动画精准自然,适合对动画精度要求高的场景,但需要等待DOM挂载完成后获取高度,不适合内容频繁动态变化的场景(如果内容高度变化,需要重新获取高度)。
  • 方案二:实现简单,无需操作DOM获取高度,但如果max-height设置过大,收起/展开的动画会显得速度不均(因为实际高度远小于max-height时,动画前半段会显得很慢),适合内容高度范围可预估的场景。

内容的提问来源于stack exchange,提问作者Fisher jion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 01:40:12