老徐WEB:swiper插件实现图片滚动轮播图(三)
老徐看到网上有用swiper来实现轮播图的,就研究了下。发现swiper挺简单的,事例介绍清晰,文档容易理解,就试着做了一个网站常用的轮播图。swiper官网提供了很多事例,有简单实用的,也有很炫的,根据自己的需要选择相应的样式。
如果对轮播图原理和制作过程不熟悉的,可以看看老徐之前的相关轮播图的两篇文章,【最简单详细的轮播图原理和制作过程】和【JS简单实现图片滚动效果轮播图,自动和手动】。
用swiper实现的轮播图效果如下:
下面详细介绍下swiper轮播图制作过程。
首先引入swiper官方的CSS和JS文件,可以去官方网站下载。
<link rel="stylesheet" href="./css/swiper.min.css" >
<script src="./js/swiper.min.js"></script>
然后搭建HTML结构。代码不多,容易理解,只是结构和类名不能更改。左右按钮和分页在此示例里都已经添加了,满足工作中常用需求。
<div class="swiper-container" id="box">
<div class="swiper-wrapper">
<div class="swiper-slide"><img src="./images/1.jpg" /></div>
<div class="swiper-slide"><img src="./images/2.jpg" /></div>
<div class="swiper-slide"><img src="./images/3.jpg" /></div>
<div class="swiper-slide"><img src="./images/4.jpg" /></div>
<div class="swiper-slide"><img src="./images/5.jpg" /></div>
</div>
<!-- 导航按钮 -->
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
<!-- 分页 -->
<div class="swiper-pagination"></div>
</div>
然后CSS样式。
<style>
body, div, img {
margin:0;
padding:0;
}
html, body {
position:relative;
height:100%;
}
body {
background-color:#eee;
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
font-size:14px;
color:#000;
}
.swiper-container {
margin-top:50px;
width:500px;
height:500px;
}
.swiper-slide {
background-color:#fff;
font-size:18px;
text-align:center;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
.swiper-slide img {
width:100%;
height:100%;
cursor:pointer;
}
/* 分页按钮样式 */
.swiper-pagination-bullet {
width: 20px;
height: 20px;
text-align: center;
line-height: 20px;
font-size: 12px;
color:#000;
opacity: 1;
background: rgba(0,0,0,0.2);
}
/* 分页当前按钮样式 */
.swiper-pagination-bullet-active {
color:#fff;
background: #007aff;
}
</style>
最后就是JS部分。先是初始化swiper实例,主要是轮播图的相关设置,比如自动循环播放、滑动速度、是否需要左右按钮等。这个事例做了鼠标触及播放区域时,播放会暂停,离开播放区域时,会自动开启播放的功能。
<script>
var mySwiper = new Swiper('.swiper-container',{
autoplay:true, // 自动播放
speed:1000, // 自动滑动开始到结束的时间(ms)
loop:true, // 无限循环
allowTouchMove:true, // 滑动,false不滑动
navigation:{ // 左右按钮
nextEl:'.swiper-button-next',
prevEl:'.swiper-button-prev',
},
pagination:{ // 分页
el:'.swiper-pagination',
clickable:true, // 分页按钮是否可点击
renderBullet:function(index,className){ // 渲染分页按钮,同时增加CSS样式
return '<span class="' + className + '">' + (index + 1) + '</span>';
},
},
on:{
click:function(){;},// 单击slide时触发函数
touchStart:function(event){;},
},
});
var box = document.getElementById('box');
box.onmouseover = function(){
mySwiper.autoplay.stop();
}
box.onmouseout = function(){
mySwiper.autoplay.start();
}
</script>
最后,swiper应用很简单,多看事例和文档,就能写出自己需要的轮播图。swiper应用也很强大,满足不同层次的需求。
勤学苦练,笨鸟先飞。
关注【老徐WEB前端开发教程】,回复:轮播图 ,即有完整代码和素材分享。
还没有评论,来说两句吧...