关于前端:横向标签点击后滚动居中

6次阅读

共计 988 个字符,预计需要花费 3 分钟才能阅读完成。

仿 IT 之家 APP 顶部的标签页成果,点击一个标签之后滚动居中到该标签页。

点击后

代码

<script setup>
import {ref, onMounted} from 'vue'

  const tabList=['三菱','宝马','雪佛兰','布加迪',
                 '柯尼塞格','兰博基尼','英菲尼迪','迈凯伦',
                 '法拉利','捷豹','公众','福特']
  const tabSelectedIndex=ref(0)
  
  const tabListRef=ref(null)
  
  const onClickTab=(index,e)=>{//console.log(tabListRef)
    //console.log(ref(e.target))
    tabSelectedIndex.value=index
    tabListRef.value.scrollLeft=e.target.offsetLeft
      -tabListRef.value.offsetLeft
      -(tabListRef.value.clientWidth-e.target.offsetWidth)/2
  }
  

</script>

<template>
  <div class="tab-list" ref="tabListRef" >
    <div class="tab" 
         :class="{'tab-selected':tabSelectedIndex===index}" 
         v-for="(tab,index) in tabList"
         @click="onClickTab(index,$event)">
      {{tab}}
    </div>
  </div>
</template>

<style>
  .tab-list{
    width:500px;
    background-color:#f8f8f8;
    display:flex;
    overflow-x:scroll;
    scroll-behavior:smooth;
    margin-left:20px;
  }
  .tab-list::-webkit-scrollbar{/*display:none;*/}
  .tab{
    flex:none;
    padding:20px 0;
    width:100px;
    text-align:center;
  }
  .tab:nth-child(odd){background-color:#eee;}
  .tab-selected{font-weight:bold;}
</style>
正文完
 0