微信小程序商城开发-商品详情轮播(图片,视频混合)
赵茂鑫 -微信小程序商品详情轮播视频+图片混合主要问题图片及视频自适应屏幕根据资源类型进行渲染滑动切换后停止视频播放滑动切换后更新资源序号所需组件swiperswiper-itemimagevideo核心代码
details.wxml
<view >
<!-- 资源数量大于等于2时才使用swiper,一个资源无需swiper,没有资源请自行处理 -->
<swiper wx:if="{{ total >= 2 }}" circular="{{ true }}" bindchange="onSwiperChange">
<swiper-item wx:for="{{ thumbs }}" wx:for-item="thumb" wx:key="index">
<image wx:if="{{ thumb.type === 'image' }}" mode="aspectFit" src={{ thumb.url }} title="{{ thumb.title }}" alt="{{ thumb.title }}"></image>
<video id="video-{{index}}" 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" 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}}" wx:if="{{ thumb.type === 'video' }}" show-fullscreen-btn="{{ false }}" src={{ thumb.url }}></video>
</view>
<view >
<text >{{ index }}</text><text >/</text><text >{{ 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)样式请自行定制~^:^~欢迎留言讨论
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。