首页 > 建站教程 > JS、jQ、TS >  js控制被点击的导航始终保持在正中间正文

js控制被点击的导航始终保持在正中间

我爱模板网遇到一个需求,如下图,导航是可以滚动的,滚动超出了容器的距离。点击导航,自动滚动到正中间:



css代码
.tabs{height:.84rem; line-height: .84rem; border-bottom: 1px solid #eee; width: 100%; box-sizing: content-box; position: fixed; left: 0; right:0; top:0; background: #fff}
.tabs .inner{width:calc(100% - 1.13rem); padding-left: .31rem; box-sizing: border-box; overflow-x: scroll; align-items: center;}
.tabs span{font-size:.29rem; position: relative; white-space: nowrap; margin-right: .2rem; padding-bottom: 0 !important}
.tabs span.on{color: #333}
.tabs span.on:after{position: absolute; width: .6rem; left:50% !important; margin-left:-.3rem; right: none !important; bottom: 0; height: .04rem; background: #F8A83B; border-radius: 999px; content: ""}
.tabs .nav-btn{position: absolute; right: .31rem; top:0; bottom: 0; padding-left:.8rem; background: linear-gradient(to right,rgba(255,255,255,0) 0%,rgba(255,255,255,1) 40%)}
.tabs .nav-btn img{width: .42rem; height: .42rem; display: block;}
html结构:
<div class="tabs">
    <div class="inner flex flex-start flex-middle">
        <span :class="item.active ? 'on':''" v-for="(item,index) in nav" tapmode @click="changeGroup(index)">{{item.txt}}</span>
    </div>
    <div class="nav-btn flex flex-middle"><img src="../../image/icon-nav.png"></div>
</div>
js代码
changeGroup:function(idx){
    this.nav.map(function(item,index){
        if(index === idx){
            item.active = true;
        }else{
            item.active = false;
        }
    })
    //当前span如果要到中间,必须将当前span到屏幕左边的距离减去屏幕的一半
    var targetSpan = document.querySelectorAll('.tabs .inner span')[idx];
    var offsetLeft = func.getOffsetLeft(targetSpan);
    var offsetWidth = targetSpan.offsetWidth;
    var parentDiv = targetSpan.parentNode;
    parentDiv.scrollLeft = offsetWidth/2+offsetLeft-api.winWidth/2;
}
注:
    js代码中用到了一个方法:getOffsetLeft,就是获取span到屏幕左边的距离,其代码如下:
var func = {
    getOffsetLeft:function(obj){
        var tmp = obj.offsetLeft;
        var val = obj.offsetParent;
        while(val != null){
            tmp += val.offsetLeft;
            val = val.offsetParent;
        }
        return tmp;
    }
}
详见:js和jQuery获取距离屏幕顶部和距离屏幕左边的距离