微信小程序瀑布流源码 微信小程序实现瀑布流

小编 09-09 11

微信小程序瀑布流是一种常见的布局方式,用于展示图片列表,能够实现图片的自适应布局,使得界面更加美观和实用,下面我将为你提供一个简单的微信小程序瀑布流源码示例,包含必要的文件和代码。

微信小程序瀑布流源码 微信小程序实现瀑布流

1. 项目结构

一个基本的瀑布流项目结构如下:

my-app/
├── app.js
├── app.json
├── app.wxss
├── pages/
│   ├── index/ 
│   │   ├── index.js
│   │   ├── index.json
│   │   ├── index.wxml
│   │   └── index.wxss
└── utils/
    └── waterfall.js

2. app.js

app.js中,我们初始化全局数据:

App({
  onLaunch: function () {
    // 应用启动时执行
  },
  globalData: {
    imageUrls: [
      'https://example.com/image1.jpg',
      'https://example.com/image2.jpg',
      // 更多图片URL
    ]
  }
})

3. app.json

app.json中,我们配置页面路径:

{
  "pages": [
    "pages/index/index"
  ],
  "window": {
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "瀑布流示例",
    "navigationBarTextStyle": "black"
  }
}

4. index.js

index.js中,我们引入瀑布流工具类,并使用它来计算图片的宽度和高度:

const waterfall = require('../../utils/waterfall.js');
Page({
  data: {
    imgList: [],
    columnWidth: 0
  },
  onLoad: function () {
    const app = getApp();
    const imgList = app.globalData.imageUrls;
    const columnWidth = this.getSystemInfoSync().windowWidth / 3;
    this.setData({
      imgList: imgList,
      columnWidth: columnWidth
    });
  },
  onReady: function () {
    waterfall(this.data.imgList, this.data.columnWidth);
  }
})

5. index.wxml

index.wxml中,我们使用wx:for循环来渲染图片列表,并使用bindtap事件处理用户点击:

<view class="container">
  <view class="waterfall" bindtap="onImageTap">
    <block wx:for="{{imgList}}" wx:key="index">
      <view class="img-item" style="width: {{item.width}}px; height: {{item.height}}px;">
        <image src="{{item.url}}" mode="aspectFill"/>
      </view>
    </block>
  </view>
</view>

6. index.wxss

index.wxss中,我们定义样式:

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.waterfall {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.img-item {
  margin-bottom: 10px;
  overflow: hidden;
}

7. utils/waterfall.js

utils/waterfall.js中,我们定义一个函数来计算图片的宽度和高度:

function waterfall(imgList, columnWidth) {
  const columnCount = 3;
  let rowHeight = [];
  for (let i = 0; i < columnCount; i++) {
    rowHeight[i] = 0;
  }
  imgList.forEach((item, index) => {
    let minHeight = Math.min(...rowHeight);
    let columnIndex = rowHeight.indexOf(minHeight);
    item.width = columnWidth;
    item.height = minHeight + columnWidth * 0.75; // 假设图片宽高比为 4:3
    rowHeight[columnIndex] += item.height;
  });
}
module.exports = {
  waterfall: waterfall
}
The End
微信