仿今日頭條 選中tab位置始終居中
HTML:
<ul class="catelist">
<li (click)="changetab(0)">
推薦
</li>
<li (click)="changetab(1)">
推薦2
</li>
<li (click)="changetab(2)">
推薦3
</li>
<li (click)="changetab(3)">
推薦4
</li>
</ul>
SCSS:
.catelist{
&::-webkit-scrollbar {
display: none;
}
background-color:#fff;
width:100%;
height: 42px;
border-top:1px solid #ededed;
white-space: nowrap;
overflow-x: scroll;
li{
font-size:14px;
display: inline-block;
margin:0px 12px;
height:40px;
line-height:40px;
color:#5a495f;
}
li.checked{
color:$mainColor;
}
}
JS:
//獲取每個item距離可視區左側的畫素值
getItemLeftPx() {
let thas = this;
//可視區寬度除2
let viewWidth = $(".catelist").width()/2;
let dom = $(".catelist>li");
let length = dom.size();
let itemleft:any = 0;
for (let i = 0; i < length; i++) {
itemleft = dom.eq(i).position().left + (dom.eq(i).width() / 2) + 12 - viewWidth;
itemleft = parseInt(itemleft);
thas.flagitemleft.push(itemleft);
}
}
//切換場景
changetab(index) {
//自動定位使用者點選的場景
$(".catelist").animate({"scrollLeft":this.flagitemleft[index]},300);
}