网上关于swiper 自定义分页器的方法比较多,但是已经不适合使用。它的API又比较坑爹,什么都是点到为止,不说清楚。因为要做一个产品颜色切换的效果,有黑与白两种颜色,因此尝试使用Swiper的自定义分页定义产品的颜色,看下图:
swiper 默认的切换是不以这种产品的颜色来定的,因此,要先写好颜色的分页器:
<div class="swiper-pagination ubolt-swiper-pagination"> <span class="swiper-pagination-bullet ubolt-black"></span> <span class="swiper-pagination-bullet ubolt-white"></span> </div>
.swiper-pagination-bullet{ width: 40px; height: 40px; border-radius: 50%; display: inline-block; opacity: .5; cursor: pointer; border: 2px solid #979797; transition: all .05s ease-in; } .ubolt-black{ background: #0E0E0E; } .ubolt-white{ background: #D8D8D8; }
在Swiper的方法中作如下定义,自定义分页器使用了 renderBullet 方法,通过判断 index 来定义产品的颜色,方法中的参数 className 我也没用到,直接 return 了两个颜色的节点:
<script> $(document).ready(function () { var mySwiper = new Swiper (\'.swiper-container\', { direction: \'horizontal\', height: 600, width: 600, loop: true, speed:1000, autoplay : { delay:3000 }, effect : \'fade\', roundLengths : true, slidesPerView: 4, spaceBetween: 40, breakpoints: { //当宽度小于等于320 320: { slidesPerView: 1, spaceBetween: 10 }, //当宽度小于等于480 480: { slidesPerView: 2, spaceBetween: 20 }, //当宽度小于等于640 640: { slidesPerView: 3, spaceBetween: 30 } }, // 如果需要分页器 pagination: { el: \'.swiper-pagination\', clickable :true, //自定义分页类型 type : \'custom\', //自定义分页 renderBullet: function (index, className) { if(index === 1){ return \'<span class="swiper-pagination-bullet ubolt-black"></span>\'; }else{ return \'<span class="swiper-pagination-bullet ubolt-white"></span>\'; } } } }) }) </script>