1. 程式人生 > 程式設計 >Swiper實現導航欄滾動效果

Swiper實現導航欄滾動效果

在一些移動app中,總能看到導航欄是可以滾動,下列例子是在vant的官方文件中看到的,這樣的滾動效果利用Swiper也可以實現,效果實現的思路是,根據當前點選的“標籤”為起點,當前標籤”的位置大於視口的一半時,讓容器的位置偏移一定的位置,讓當前點選的“標籤”始終在視口的中間位置。

Swiper實現導航欄滾動效果

1、引入相關外掛

<link rel="stylesheet" href="../css/swiper.css" >
<script src="http://www.jq22.com/jquery/jquery-1.7.1.js"></script>
<script src="../js/swiper.js"></script>

2、編寫view(介面)

<div class="box">
 <div class="swiper-container">
 <div class="swiper-wrapper">
 <div class="swiper-slide">綜合</div>
 <div class="swiper-slide">單曲</div>
 <div class="swiper-slide">視訊</div>
 <div class="swiper-slide">歌手</div>
 <div class="swiper-slide">專輯</div>
 <div class="swiper-slide">歌單</div>
 <div class="swiper-slide">主播電臺</div>
 <span></span>
 </div>
 </div>
</div>

3、編寫style

*{
 margin: 0;
 padding: 0;
 }
 .box{
 width: 500px;
 height: 50px;
 border: 1px solid #000;
 margin: 100px auto;
 }
 .swiper-container{
 width: auto!important;
 height: 100%;
 text-align: center;
 line-height: 50px;
 color: #000;
 font-size: 20px;
 }
 .swiper-wrapper{
 position: relative;
 width: auto!important;
 height: 100%;
 }
 .swiper-slide {
 list-style: none;
 display: flex;
 justify-content: flex-start;
 flex-wrap: nowrap;
 cursor: pointer;
 }
 .swiper-wrapper span{
 position: absolute;
 height: 3px;
 background: #000;
 left: 1%;
 top: 85%;
 }
 .swiper-slide{
 width: auto!important;
 margin-right: 15px!important;
 padding: 0 18px;
 }

為了讓每個swiper-slide的寬度由內容撐起,右邊顯示一半是提示使用者這個導航欄是可以滾動的,所以在初始化時要設定swiper的slidesPerView為auto,slidesPerView: “auto”,同時要在css設定swiper-slide的樣式為:

 .swiper-slide{
 width: auto!important;
 margin-right: 15px!important;
 padding: 0 18px;
 }

Swiper實現導航欄滾動效果

這樣swiper-slide的寬度就是由內容撐起了,而且可以自由的進行滾動了

Swiper實現導航欄滾動效果

4、編寫js

$(function () {
 $(".swiper-wrapper span").css({width: $(".swiper-slide")[0].offsetWidth});
 let navScroll = new Swiper('.box .swiper-container',{
 freeMode:true,slidesPerView: "auto",freeModeMomentumRatio: 0.5,on:{
 //當前swiper-slide點選時觸發事件
 click:function (e) {
  let thisWidth = this.clickedSlide.offsetWidth;
  let thisLeft = this.clickedSlide.offsetLeft;
  let offsetX = this.width / 2 - thisLeft - thisWidth / 2;
  //偏移量在1/2視口內時,容器不發生偏移
  if (offsetX > 0){
  offsetX = 0;
  }
  //offsetX小於容器最大偏移時,讓偏移量等於容器最大的偏移量
  else if (offsetX < this.maxTranslate()){
  offsetX = this.maxTranslate();
  }
  //設定容器的過渡動畫
  this.setTransition(300);
  this.setTranslate(offsetX);
  //滾動條位置和長度執行動畫
  $(".swiper-wrapper span").animate({left: thisLeft,width: thisWidth},400);
 }
 }
 });
 })

最終效果

Swiper實現導航欄滾動效果

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。