前段时间做移动项目,设计稿上有个菜单点击后回弹到页面中间的位置,很像头条菜单的效果,就度娘爬了几个小时,终于找到个能用的jquery+swiper(5.3以上版本,否则clickedIndex参数不识别)实现仿头条顶部菜单,点击菜单该菜单回滚到中间的效果。不多逼叨,一起先看效果,后复制代码!

css代码:

#topNav{width:86vw;overflow:hidden;border-bottom:1px solid #f8f8f8;}
#topNav .swiper-slide{width:3rem;padding: 0 5px;letter-spacing:2px;text-align:center;}
#topNav .swiper-slide span{transition:all .3s ease;display:block;font-size: 4.5vw;color: #333;line-height: 12vw;}
#topNav .active span{transform:scale(1.1);color:#2BD9B4;}
.swiper-slide {-webkit-flex-shrink: 0;-ms-flex: 0 0 auto;flex-shrink: 0;width: 100%;height: 100%;position: relative;}
.swiper-wrapper {position: relative;width:100%;height: 100%;z-index: 1;display: -webkit-box;display: -moz-box; display: -ms-flexbox;display: -webkit-flex;display: flex;-webkit-transition-property: -webkit-transform;-moz-transition-property: -moz-transform;-o-transition-property: -o-transform;-ms-transition-property: -ms-transform;transition-property: transform;-webkit-box-sizing: content-box;-moz-box-sizing: content-box; box-sizing: content-box;} 

html代码:

<div id="topNav">
<div class="swiper-wrapper">
<div class="swiper-slide active"><span>推荐</span></div>
<div class="swiper-slide"><span>热点</span></div>
<div class="swiper-slide"><span>深圳</span></div>
<div class="swiper-slide"><span>视频</span></div>
<div class="swiper-slide"><span>社会</span></div>
<div class="swiper-slide"><span>娱乐</span></div>
<div class="swiper-slide"><span>科技</span></div>
<div class="swiper-slide"><span>问答</span></div>
<div class="swiper-slide"><span>汽车</span></div>
<div class="swiper-slide"><span>财经</span></div>
<div class="swiper-slide"><span>军事</span></div>
<div class="swiper-slide"><span>体育</span></div>
<div class="swiper-slide"><span>段子</span></div>
<div class="swiper-slide"><span>美女</span></div>
<div class="swiper-slide"><span>国际</span></div>
<div class="swiper-slide"><span>趣图</span></div>
<div class="swiper-slide"><span>健康</span></div>
<div class="swiper-slide"><span>特产</span></div>
<div class="swiper-slide"><span>房产</span></div>
</div>
</div>

js代码:

//点击滚动菜单
var topNav = new Swiper('#topNav', {
freeMode: true,
freeModeMomentumRatio: 0.5,
centeredSlides: true,
centeredSlidesBounds: true,
slidesPerView: 'auto',
on: {
tap: function() {
$("#topNav  .active").removeClass('active');
$("#topNav .swiper-slide").eq(this.clickedIndex).addClass('active');
topNav.slideTo(this.clickedIndex);
}
}
})

注意:要引入"swiper.js"5.0以上版本,没有的去官方下载,就不啰嗦了!

最后,推广一下我自己开发的wp主题:Qui-Pure,同时也在用,就是当前你看到的UI主题界面,主题永久免费,顶部菜单就可以下载!