1. 程式人生 > >頭部導航,使點選一個欄目滑動到螢幕中間--多用於移動端

頭部導航,使點選一個欄目滑動到螢幕中間--多用於移動端

HTML程式碼:

<ul class="tab-head">

  <li class="tab-head-item active">心理諮詢師</li>

       <li class="tab-head-item">心理學技術與流派</li>

       <li class="tab-head-item">學校心理健康</li>

       <li class="tab-head-item">大眾心理學</li>

       <li class="tab-head-item">考研課程</li>

      <li class="tab-head-item">心理學大會</li>

</ul>

CSS程式碼:

.tab-head::-webkit-scrollbar{
  display: none;
}

.tab-head{
  margin: 0 auto;
  list-style-type: none;
  display:flex;
  flex-wrap:nowrap;
  justify-content:space-between;
  background: #fff;
       padding: 0;
  overflow: auto;
  height: 46px;
  border-bottom: 1px solid #B0B0B0;
  position: fixed;
  top: 0;
  z-index: 9;
}

.tab-head-item{
  flex:1 0 auto;
  color: #333;
  padding: 0 5px;
  height: 46px;
  line-height: 46px;
}

.active{
  color: #c50808;
  position: relative;
}

.active:after{ content: "";display: block;height: 3px;width:35px;background: #c50808;position: absolute; bottom: 0;left:0;right:0;margin:auto;border-radius: 10px;} 

 

JS程式碼:

 

$(".tab-head li").click(function(){
// alert(11)
var moveX = $(this).position().left+$(this).parent().scrollLeft();
        var pageX = document.documentElement.clientWidth;//裝置的寬度
        var blockWidth = $(this).width();
  // console.log(moveX);
  //                  console.log(pageX);
  //                console.log(blockWidth);
  var left = moveX-(pageX/2)+(blockWidth/2);
$(".tab-head").animate({scrollLeft:left},400);
        $(this).addClass("active").siblings().removeClass("active");
});