Swiper實現(xiàn)導航欄滾動效果
在一些移動app中,總能看到導航欄是可以滾動,下列例子是在vant的官方文檔中看到的,這樣的滾動效果利用Swiper也可以實現(xiàn),效果實現(xiàn)的思路是,根據(jù)當前點擊的“標簽”為起點,當前標簽”的位置大于視口的一半時,讓容器的位置偏移一定的位置,讓當前點擊的“標簽”始終在視口的中間位置。
1、引入相關(guān)插件
<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的寬度由內(nèi)容撐起,右邊顯示一半是提示用戶這個導航欄是可以滾動的,所以在初始化時要設(shè)置swiper的slidesPerView為auto,slidesPerView: “auto”, 同時要在css設(shè)置swiper-slide的樣式為:
.swiper-slide{ width: auto!important; margin-right: 15px!important; padding: 0 18px; }
這樣swiper-slide的寬度就是由內(nèi)容撐起了,而且可以自由的進行滾動了
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視口內(nèi)時,容器不發(fā)生偏移 if (offsetX > 0){ offsetX = 0; } //offsetX小于容器最大偏移時,讓偏移量等于容器最大的偏移量 else if (offsetX < this.maxTranslate()){ offsetX = this.maxTranslate(); } //設(shè)置容器的過渡動畫 this.setTransition(300); this.setTranslate(offsetX); //滾動條位置和長度執(zhí)行動畫 $(".swiper-wrapper span").animate({left: thisLeft, width: thisWidth},400); } } }); })
最終效果
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript?顯示一個倒計時廣告牌的實現(xiàn)示例
本文主要介紹了JavaScript?顯示一個倒計時廣告牌的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04Bootstrap整體框架之JavaScript插件架構(gòu)
這篇文章主要介紹了Bootstrap整體框架之JavaScript插件架構(gòu)的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12