需求:
1、轮播图自动播放
2、轮播图根据后端返回是放图片或者是视频
3、点击播放视频,手动切换轮播图后,视频暂停播放
技术:
swiper+video
<template>
<view class="container">
<view>
<!-- 轮播图 -->
<swiper indicator-dots="true" indicator-color='#fff' indicator-active-color='#0086d6' :autoplay="autoplay"
interval="3000" duration="1500" show-center-play-btn="true" class="swiper-box" circular='true'
@change="swiperChange">
<swiper-item v-for="(item ,index) in Banners" :key="index">
<view class="swiper-item" v-show="!splits(item)" wx-if="{item}">
<image v-if="item" :src="item" mode="widthFix"></image>
</view>
<view class="swiper-item" v-show="splits(item)" v-if="item">
<video :id="'myVideo'+index" :autoplay="false" :src="item" controls object-fit="cover"
@play="play" @pause="pause" @ended="ended" auto-pause-if-navigate
auto-pause-if-open-native></video>
</view>
</swiper-item>
</swiper>
</view>
</template>
<script>
export default {
data() {
return {
Banners: [], //轮播图
autoplay: true, //自动切换轮播图
videoContext: '',
};
},
onLoad() {
let that = this
this.GetBanner()
},
methods: {
swiperChange(e) {
let {
current,
source
} = e.detail
this.videoContext = uni.createVideoContext('myVideo' + (current - 1));
//只有手动切换时开始轮播,并且上一页视频暂停
if (source === 'touch') {
this.videoContext.pause(); //暂停
this.autoplay = true
}
},
// 获取数据
GetBanner() {
this.api.GetBanner().then(res => {
this.Banners = res.data.Data.Banners
})
},
// 处理banner返回的是是视频还是图片
splits(url) {
if (url.indexOf('.') != -1) {
var ext = url.substring(url.lastIndexOf('.') + 1);
return ['mp4', 'webm', 'mpeg4', 'ogg'].indexOf(ext) != -1
}
},
// 点击开始/继续播放
play() {
this.autoplay = false
// this.videoContext.requestFullScreen()
},
// 视频暂停
pause() {
this.autoplay = true
},
// 视频结束
ended() {
this.autoplay = true
},
}
}
</script>
<style lang="scss">
page {
background-color: #FFFFFF;
}
.container {
font-size: 14px;
background-color: #fff;
height: 100%;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.swiper-box {
height: 350rpx;
}
.swiper-item {
display: flex;
image {
width: 100%;
height: 350rpx;
}
video {
width: 100%;
height: 350rpx;
}
}
.rightbox {
display: block;
width: 100%;
}
.imgleft {
display: block;
// margin: 20rpx 17rpx 20rpx 0;
margin: 8px auto;
width: 75px;
height: 65px;
}
.imgright {
width: 17px !important;
height: 16px !important;
padding: 0 !important;
margin-top: 10px;
float: right;
}
.sh {
width: 100%;
text-align: center;
margin-top: 10rpx;
}
.img {
height: 20px;
width: 180px;
}
</style>