1. 程式人生 > 程式設計 >原生JS封裝vue Tab切換效果

原生JS封裝vue Tab切換效果

本文例項為大家分享了原生js封裝vue Tab切換的具體程式碼,供大家參考,具體內容如下

先看效果圖

原生JS封裝vue Tab切換效果

使用的技術

vue,js,css3

vue元件 可以直接使用

<template>
  <div class="bookcircle-header">
    <ul class="wrapper" :class="headerActive == 0 ? 'friend' : 'booklist'">
      <li @click="headerChange(0)" :class="headerActive == 0 ? 'active' : ''">
        書友
      </li>
      <li @click="headerChange(1)" :class="headerActive == 1 ? 'active' : ''">
        書單
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  components: {},data() {
    return {
      headerActive: 0,};
  },computed: {},created() {},mounted() {
    //初始化拋發
    this.$emit("change",this.headerActive);
  },mhttp://www.cppcns.com
ethods: { http://www.cppcns.com headerChange(index) { this.headerActive = index; this.$emit("change",index); },},}; </script> <style lang="less" scoped> .bookcircle-header { height: 42px; display: flex; justify-content: center; align-items: center; .wrapper { width: 286px; font-size: 14px; height: 29px; color: #1489fe; border: 1px solid #1489fe; border-radius: 14px; display: flex; justif
程式設計客棧
y-content: center; align-items: center; position: relative; box-sizing: border-box; // 解決邊框溢位,將border包含在盒子內部 li { flex: 1; height: 100%; display: flex; justify-content: center; align-items: center; z-index: 2; } .active { col程式設計客棧or: white; } &::before { content: ""; width: 143px; height: 100%; background-color: #1489fe; position: absolute; top: 0px; left: 0px; border-radius: 13px 0px 0px 13phttp://www.cppcns.com
x; z-index: 1; transition: all 0.3s; } &.firend::before { transform: translateX(0); border-radius: 13px 0px 0px 13px; } &.booklist::before { transform: translateX(100%); border-radius: 0px 13px 13px 0px; } } } </style>

實現原理:

使用ul,li以及彈性盒子,首先給父元素設定寬高,然後通過彈性盒子將子元素 li 水平方向展開, 給子元素 li 設定 flex:1,讓子元素平分父元素的寬。

然後給父元素設定偽元素,以絕對定位的方式覆蓋第一個 li 元素, 通過z-index屬性,控制偽元素和子元素的層級顯示關係。

然後給偽元素設定 transition 屬性 搭配 transform: translateX(); 屬性,讓元素水平移動就可以了

注意點:

1、雖然切換的點選事件在子元素上,並且也給子元素新增 了active樣式,但tab的切換效果並不是通過子元素來實現的,而是通過父元素的偽元素來實現切換效果。
2、必須要根據子元素的 index 給父元素設定動態class,這樣父元素的偽元素才能根據選中的子元素執行切換動畫
3、本元件使用的是 淘寶amfe-flexible、 postcss適配,使用時注意適配問題

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。