tab菜单点击选中状态始终在屏幕可视区内

<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>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值