Swiper實現導航欄滾動效果
更新時間:2020年10月16日 09:55:25 作者:HAN_韓
這篇文章主要為大家詳細介紹了Swiper實現導航欄滾動效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
在一些移動app中,總能看到導航欄是可以滾動,下列例子是在vant的官方文檔中看到的,這樣的滾動效果利用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-slide的寬度就是由內容撐起了,而且可以自由的進行滾動了

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點擊時觸發(fā)事件
click:function (e) {
let thisWidth = this.clickedSlide.offsetWidth;
let thisLeft = this.clickedSlide.offsetLeft;
let offsetX = this.width / 2 - thisLeft - thisWidth / 2;
//偏移量在1/2視口內時,容器不發(fā)生偏移
if (offsetX > 0){
offsetX = 0;
}
//offsetX小于容器最大偏移時,讓偏移量等于容器最大的偏移量
else if (offsetX < this.maxTranslate()){
offsetX = this.maxTranslate();
}
//設置容器的過渡動畫
this.setTransition(300);
this.setTranslate(offsetX);
//滾動條位置和長度執(zhí)行動畫
$(".swiper-wrapper span").animate({left: thisLeft, width: thisWidth},400);
}
}
});
})
最終效果

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

