微信小程序商品详情轮播视频+图片混合
次要问题
- 图片及视频自适应屏幕
- 依据资源类型进行渲染
- 滑动切换后进行视频播放
- 滑动切换后更新资源序号
所需组件
- swiper
- swiper-item
- image
- video
外围代码
details.wxml
<view class="thumbs"> <!-- 资源数量大于等于2时才应用swiper,一个资源无需swiper,没有资源请自行处理 --> <swiper wx:if="{{ total >= 2 }}" circular="{{ true }}" style="height: {{width}}px;" bindchange="onSwiperChange"> <swiper-item wx:for="{{ thumbs }}" wx:for-item="thumb" wx:key="index"> <image style="width: 100%; height: 100%;" class="thumb" wx:if="{{ thumb.type === 'image' }}" mode="aspectFit" src="{{ thumb.url }}" title="{{ thumb.title }}" alt="{{ thumb.title }}"></image> <video id="video-{{index}}" style="width: 100%; height: 100%;" class="video" wx:if="{{ thumb.type === 'video' }}" show-fullscreen-btn="{{ false }}" src="{{ thumb.url }}"></video> </swiper-item> </swiper> <view wx:else> <!-- 单个资源时, 请留神通过style属性设置其width,heigth属性,否则不会显示--> <image wx:for="{{ thumbs }}" wx:for-item="thumb" wx:key="index" style="width:{{width}}px; height:{{width}}px;" class="thumb" wx:if="{{ thumb.type === 'image' }}" mode="aspectFit" src="{{ thumb.url }}" title="{{ thumb.title }}" alt="{{ thumb.title }}"></image> <video wx:for="{{ thumbs }}" wx:for-item="thumb" wx:key="index" id="video-{{index}}" style="width:{{width}}px; height:{{width}}px;" class="video" wx:if="{{ thumb.type === 'video' }}" show-fullscreen-btn="{{ false }}" src="{{ thumb.url }}"></video> </view> <view class="counter"> <text class="index">{{ index }}</text><text class="spec">/</text><text class="total">{{ total }}</text> </view></view>
details.js
Page { data: { index: 0, total: 0, width: 0, thumbs: [] }, onSwiperChange (e) { // 推断前后资源索引,用于切换时进行视频播放,如无此需要能够省略 const prev = index >= 1 ? index - 1 : this.data.total - 1 const next = index <= this.data.total - 2 ? index + 1 : 0; // 可能从左向右滑 if (this.data.thumbs[prev].type === 'video') { const videoContext = wx.createVideoContext('video-' + prev) //这里对应的视频id videoContext.pause(); // 进行播放 } // 可能从右向左滑 if (this.data.thumbs[next].type === 'video') { const videoContext = wx.createVideoContext('video-' + next) //这里对应的视频id videoContext.pause(); // 进行播放 } // 更新以后序号 this.setData({ index: index + 1 }) }, loadProductThumbs () { // 省略获取数据逻辑,依据数据汇合设置total值 const _this = this; // 数据结构 /* { type: 'image||video', url: '...', ...其余数据 } */ wx.request({ url: '', success: (res) => { _this.setData({ total: res.data.list.length, // 采纳增量更新形式(轻易了) thumbs: [...this.data.thumbs, ...res.data.list] }) } }) }, onLoad () { // 获取屏幕宽度, 使图片或者视频宽度为全屏宽度,高度与宽度统一,高宽可依据需要自行设置 this.loadProductThumbs() const { screenWidth } = wx.getSystemInfoSync() this.setData({ width: screenWidth }); }}
details.wxss
.thumbs { position: relative;}.thumbs .counter { position: absolute; bottom: 10px; right: 10px; padding: 2px 8px; border-radius: 12px; background-color: #0000008a; color: #fafafa;}
计数器(counter)款式请自行定制~^:^~
欢送留言探讨