头部导航,使点击一个栏目滑动到屏幕中间--多用于移动端

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");
});

猜你喜欢

转载自www.cnblogs.com/w1991/p/9809003.html