使用Swiper.js轮播图插件实现当前活动块元素有video视频时swiper停止自动切换,监听视频播放结束再继续自动切换到下一个的效果。实现该效果需要用到swiper事件有slideChangeTransitionEnd(swiper)、用到swiper的方法有mySwiper.autoplay.stop()、mySwiper.autoplay.start()。
实现代码
HTML代码
<div class="swiper" id="slides"> <div class="swiper-wrapper"> <div class="swiper-slide"> <video src="upload/video.mp4" webkit-playsinline="true" playsinline="true" x5-video-player-type="h5" x5-video-player-fullscreen="true" x-webkit-airplay="allow" x5-video-orientation="portraint" muted> </video> </div> <div class="swiper-slide">slider2</div> <div class="swiper-slide"> <video src="upload/video.mp4" webkit-playsinline="true" playsinline="true" x5-video-player-type="h5" x5-video-player-fullscreen="true" x-webkit-airplay="allow" x5-video-orientation="portraint" muted> </video> </div> </div> </div>
JS代码
new Swiper('#slides',{
slidesPerView: 1,
loop:false,
autoplay: true,
speed:1000,
on: {
init:function(){
var _this = this;
var _active = $('.slides .swiper-slide-active video');
if(_active.length > 0){
_this.autoplay.stop();
}
},
slideChangeTransitionEnd: function(){
var _this = this;
var _active = $('.slides .swiper-slide-active video');
if(_active.length > 0){
_this.autoplay.stop();
var _videoDom = _active[0];
_videoDom.play();
_videoDom.addEventListener('ended', function(){
_videoDom.currentTime = 0;
_this.slideNext();
_this.autoplay.start();
},false);
}
},
}
});PS:
和前面SuperSlide.js插件实现的方法基本一样,事实上大部分轮播插件都可以使用该方法实现相同的效果。
多个视频建议在轮播到当前元素时使用js插入video标签,轮播后再删除video标签的方式才能正常使用。
优化代码:
HTML代码:
<div class="swiper" id="slides"> <div class="swiper-wrapper"> <div class="swiper-slide"> <div class="video" data-video="upload/video.mp4"></div> </div> <div class="swiper-slide">slider2</div> <div class="swiper-slide"> <div class="video" data-video="upload/video.mp4"></div> </div> </div> </div>
JS代码:
/**/
new Swiper('#slides',{
slidesPerView: 1,
loop:true,
autoplay: true,
speed:1000,
on: {
slideChangeTransitionStart: function(){
var _this = this;
var _swiperSlideActive = $('#slides .swiper-slide-active');
var _swiperVideoUrl = _swiperSlideActive.find('.video').data('video');
if(_swiperVideoUrl){
_this.autoplay.stop();
var _swiperVideoHtml = '<video src="'+_swiperVideoUrl+'" webkit-playsinline="true" playsinline="true" x5-video-player-type="h5" x5-video-player-fullscreen="true" x-webkit-airplay="allow" x5-video-orientation="portraint" muted></video>';
_swiperSlideActive.find('.video').html(_swiperVideoHtml);
var _swiperVideoObj = _swiperSlideActive.find('video')[0];
_swiperVideoObj.play();
_swiperVideoObj.addEventListener('ended', function(){
_this.slideNext();
_this.autoplay.start();
},false);
}
},
slideChangeTransitionEnd: function(){
var _swiperSlideActive = $('#slides .swiper-slide-active');
_swiperSlideActive.siblings('.swiper-slide').find('.video').html('');
}
}
});PS:使用动态加载,避免一次加载多个video视频,影响网页加载速度。