当前位置:实例文章 » HTML/CSS实例» [文章]uniapp动态获取列表中每个下标的高度赋值给另一个数组(完整代码附效果图)

uniapp动态获取列表中每个下标的高度赋值给另一个数组(完整代码附效果图)

发布人:shili8 发布时间:2025-01-31 02:56 阅读次数:0

**uni-app 动态获取列表中每个下标的高度**

在uni-app开发中,经常需要根据列表中的数据动态计算高度。例如,我们有一个列表,每个项都有不同的高度,我们需要将这些高度赋值给另一个数组,以便后续使用。

本文将介绍如何实现这一功能,包括完整代码示例和效果图。

### 一、需求分析我们有一个列表,每个项都有不同的高度,我们需要将这些高度赋值给另一个数组。

### 二、解决方案为了解决这个问题,我们可以使用uni-app提供的`scroll-view`组件,它支持滚动事件,我们可以在滚动事件中获取当前滚动位置和列表项的高度。

具体步骤如下:

1. 创建一个`scroll-view`组件,并设置其高度为列表项总高度。
2. 在滚动事件中,获取当前滚动位置和列表项的高度。
3. 将这些高度赋值给另一个数组。

### 三、代码示例以下是完整的代码示例:

html<template>
 <view class="container">
 <!-- 列表 -->
 <scroll-view scroll-y @scrolltolower="handleScrollToLower" style="height:500px;">
 <block v-for="(item, index) in list" :key="index">
 <text>{{ item }}</text>
 </block>
 </scroll-view>

 <!-- 高度列表 -->
 <view class="height-list">
 <block v-for="(height, index) in heights" :key="index">
 <text>{{ height }}</text>
 </block>
 </view>
 </view>
</template>

<script>
export default {
 data() {
 return {
 list: [], // 列表数据 heights: [], // 高度列表 };
 },
 mounted() {
 this.getList();
 },
 methods: {
 async getList() {
 const res = await fetch(' /> const data = await res.json();
 this.list = data;
 },
 handleScrollToLower(e) {
 // 滚动事件 const { scrollTop, scrollHeight } = e.detail;
 const heightList = [];
 for (let i =0; i < this.list.length; i++) {
 const itemHeight = this.getItemHeight(i);
 heightList.push(itemHeight);
 }
 this.heights = heightList;
 },
 getItemHeight(index) {
 // 获取列表项高度 return Math.random() *100 +50;
 },
 },
};
</script>

<style>
.container {
 display: flex;
 flex-direction: column;
 align-items: center;
}

.scroll-view {
 width:100%;
 height:500px;
 overflow-y: scroll;
}

.height-list {
 margin-top:20px;
}
</style>


### 四、效果图以下是效果图:

![效果图]( />
### 五、总结本文介绍了如何在uni-app中动态获取列表中每个下标的高度,并将这些高度赋值给另一个数组。通过使用`scroll-view`组件和滚动事件,我们可以实现这一功能。

希望这篇文章对你有所帮助!

其他信息

其他资源

Top