1. 程式人生 > 其它 >tab選單點選選中狀態始終在螢幕可視區內

tab選單點選選中狀態始終在螢幕可視區內

技術標籤:jshtml

<template>
  <div class="hello">
    <div class="flash-list">
      <div class="scroll-box">
        <div
          v-for="(item, index) in tabArr"
          :key="index"
          ref="pageContainer"
class="flash-item-info" :class="active === index ? 'active' : ''" @click="changeFlash(index, $event)" > <span class="desc">{{ item.title }}</span> </div> </div> </div>
</div> </template> <script> export default { name: "HelloWorld", props: { msg: String, }, data() { return { tabArr: [ { title: "第1個", }, { title: "第2個", }, { title:
"第3個", }, { title: "第4個", }, { title: "第5個", }, { title: "第6個", }, { title: "第7個", }, { title: "第8個", }, { title: "第9個", }, { title: "第10個", }, ], currentIndex: 0, active: 0, }; }, methods: { // 頭部切換 changeFlash(index, event) { this.active = index; const spanLeft = event.clientX; //當前點選的元素左邊距離 const totalWidths = document.body.clientWidth; //螢幕總寬度 const widths = totalWidths / 2; //一半的螢幕寬度 const spanRight = totalWidths - spanLeft; //元素的右邊距離 const scrollBox = document.getElementsByClassName("flash-list"); //獲取最外層的元素 const scrollL = scrollBox[0].scrollLeft; //滾動條滾動的距離 if (spanLeft > widths || spanRight > widths) { //當元素左邊距離大於螢幕一半寬度 或者 右邊距離大於螢幕一半距離的時候 scrollBox[0].scrollLeft = scrollL + (spanLeft - widths); //滾動條最終的滾動距離 } }, }, }; </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> .hello { width: 100%; } .flash-list { width: 100%; height: 40px; position: relative; overflow-x: scroll; overflow-y: hidden; } .scroll-box { position: absolute; height: 40px; left: 0; display: flex; flex-flow: row nowrap; } .flash-item-info { width: 50px; height: 40px; display: flex; flex-flow: column nowrap; justify-content: space-around; align-items: center; padding: 0 10px; } .active { color: aqua; } </style>