微信小程序scroll-view做图片横向滚动

        <scroll-view class="image-group" scroll-x="true">
          <image src="../../images/background_image1@2x.png"></image>
          <image src="../../images/background_image1@2x.png"></image>
          <image src="../../images/background_image1@2x.png"></image>
          <image src="../../images/background_image1@2x.png"></image>
          <image src="../../images/background_image1@2x.png"></image>
          <image src="../../images/background_image1@2x.png"></image>
        </scroll-view>
.image-group {
  display: flex;
  white-space: nowrap;
  margin-top: 30rpx;
}
.image-group image {
  display: inline-block;
  width: 375rpx;
  height: 180rpx;
  margin-right: 20rpx;
}

关键点是五个:

1、scroll-view标签

2、scroll-x=“true”属性

3、使用display:flex 让图片横向排列

4、使用 white-space: nowrap,让图片不换行

5、图片设置inline-block


效果图:

 

### 微信小程序 `scroll-view` 横向滚动导航栏示例 以下是实现微信小程序中 `scroll-view` 组件作为顶部导航栏的横向滚动效果的具体方法: #### 页面结构 (WXML) ```html <view class="nav-container"> <scroll-view scroll-x="true" scroll-with-animation="true" style="white-space: nowrap; display: flex;" bindscroll="onScroll" lower-threshold="-100"> <view wx:for="{{categories}}" wx:key="index" class="nav-item" data-index="{{index}}" id="{{item.id}}" style="display: inline-block;" bindtap="handleNavClick"> {{item.name}} </view> </scroll-view> </view> <view class="content-container"> <!-- 这里可以放置其他内容 --> </view> ``` #### 样式 (WXSS) ```css .nav-container { overflow: hidden; } .scroll-view { width: 100%; height: 80rpx; line-height: 80rpx; white-space: nowrap; display: flex; } .nav-item { padding: 0 20rpx; font-size: 30rpx; } ``` #### 数据与逻辑 (JS) ```javascript Page({ data: { categories: [ { id: 'category_1', name: '分类一' }, { id: 'category_2', name: '分类二' }, { id: 'category_3', name: '分类三' }, { id: 'category_4', name: '分类四' } ], rightId: '' }, handleNavClick(e) { const index = e.currentTarget.dataset.index; this.setData({ rightId: this.data.categories[index].id }); }, onScroll() { // 可在此处理滚动事件,例如加载更多数据等 } }); ``` --- 上述代码实现了以下功能: - 使用 `scroll-view` 的 `scroll-x=true` 属性开启横向滚动[^4]。 - 子元素通过 `style="display: inline-block"` 确保能够正常排列。 - 利用 `bindtap` 和 `data-*` 属性绑定点击事件,动态更新 `rightId` 值来控制滚动位置[^1]。 #### 关键点说明 1. **`scroll-into-view` 功能** 当前页面会根据 `scroll-into-view={{rightId}}` 自动滚动到对应的子元素位置[^3]。因此,在每次点击导航项时,需同步更新该变量值。 2. **样式调整** 需要为父容器设置 `white-space: nowrap` 和 `display: flex` 来支持多列布局下的水平滚动。 3. **性能优化** 如果列表较长,建议结合虚拟化技术减少渲染压力;同时可以通过监听滚动事件 (`bindscroll`) 实现懒加载等功能[^2]。 --- ###
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值