swiper做导航栏,并且点击的时候导航栏会滑动居中
时间: 2024-02-15 11:04:40 浏览: 65
以下是一个使用Swiper做导航栏,并且点击的时候导航栏会滑动居中的示例代码:
HTML结构:
```
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide"><a href="#">导航1</a></div>
<div class="swiper-slide"><a href="#">导航2</a></div>
<div class="swiper-slide"><a href="#">导航3</a></div>
<div class="swiper-slide"><a href="#">导航4</a></div>
<div class="swiper-slide"><a href="#">导航5</a></div>
<div class="swiper-slide"><a href="#">导航6</a></div>
<div class="swiper-slide"><a href="#">导航7</a></div>
<div class="swiper-slide"><a href="#">导航8</a></div>
<div class="swiper-slide"><a href="#">导航9</a></div>
</div>
</div>
```
CSS样式:
```
.swiper-slide {
text-align: center;
}
.swiper-slide a {
display: block;
padding: 10px;
color: #333;
text-decoration: none;
}
.swiper-pagination-bullet-active a {
color: blue;
}
```
JS代码:
```
var swiper = new Swiper('.swiper-container', {
slidesPerView: 3,
spaceBetween: 30,
centeredSlides: true,
pagination: {
el: '.swiper-pagination',
clickable: true,
renderBullet: function(index, className) {
return '<span class="' + className + '"><a href="#">' + (index + 1) + '</a></span>';
},
},
on: {
click: function() {
var activeIndex = this.activeIndex;
var slidesLength = this.slides.length;
var paginationLength = this.pagination.bullets.length;
var half = Math.floor(this.params.slidesPerView / 2);
if (activeIndex < half) {
this.slideTo(0);
} else if (activeIndex >= slidesLength - half) {
this.slideTo(slidesLength - this.params.slidesPerView);
} else {
this.slideTo(activeIndex - half);
}
}
}
});
```
这个示例中,我们创建了一个包含9个导航链接的Swiper导航栏。Swiper的slidesPerView参数设置为3,表示每次显示3个导航链接,spaceBetween参数设置为30,表示每个导航链接之间的间距为30px。Swiper的centeredSlides参数设置为true,表示当前显示的导航链接居中显示。Swiper的pagination参数设置为true,表示显示分页器,clickable参数设置为true,表示点击分页器可以切换到对应的导航链接。Swiper的on事件监听了点击事件,并在点击后调用slideTo方法滑动到当前导航链接居中显示的位置。
阅读全文