1

vue自定义横向滚动条,导航两行排列布局

需求说明

需求点主要有两个

  1. 接口返回的导航数组,要从上到下,从左到右排列,导航的个数是可配置的。
  2. 滚动条的长度跟滚动容器长度不一样,需要自己手动模拟滚动条。

效果

代码实现

  • html:

    <div class="home-nav-container">
    <ul
      class="home-nav nav-container"
      :style="floorStyle"
      @scroll="getLeft"
    >
      <li
        v-for="(item, index) in floors"
        :key="index"
      >
        <img class="nav-icon" :src="item.headImg" alt="" />
      </li>
    </ul>
    <div v-if="slideShow" class="slide">
      <div class="slide-bar">
        <div class="slide-show" :style="`width:${slideWidth}px;margin-left:${slideLeft<=1 ? 0 : slideLeft}px`"></div>
      </div>
    </div>
    </div>
  • js:

    export default {
    data() {
      return {
        slideWidth: 0, // 滑块宽
        slideLeft: 0, // 滑块位置
        slideShow: false, // 是否显示滑块
        slideRatio: 0, // 滑块比例
        lengthRatio: 0, // 列表长度与屏幕长度比例(每个Item占20%屏幕长度)
      };
    },
    created() {
      this.getRatio();
    },
    mounted() {
      window.addEventListener('scroll', this.getLeft);
    },
    methods: {
      getRatio() {
        if (this.floor.rooms.length <= 10) {
          this.slideShow = false;
        } else {
          this.lengthRatio = Math.floor(this.floor.rooms.length / 2) / 5; // 列表长度与屏幕长度比例(每个Item占20%屏幕长度)
          this.slideRatio = 40 / (375 * this.lengthRatio); // 滚动列表长度与滑条长度比例
          this.slideWidth = 40 / this.lengthRatio; // 当前显示蓝色滑条的长度(保留两位小数)
          this.slideShow = true;
        }
      },
      // slideLeft动态变化
      getLeft(e) {
        this.slideLeft = e.target.scrollLeft * this.slideRatio;
      },
    },
    };
  • css:

    .home-nav-container {
    background-color: #fff;
    position: relative;
    background-size: 100% 100%;
    margin: 0.05rem 0.24rem;
    border-radius: 0.2rem;
    .home-nav {
      display: flex;
      flex-wrap: wrap;
      &.nav-container {
        display: flex;
        flex-wrap: wrap;
        flex-direction: column;
        max-height: 3.48rem;
        overflow-x: scroll;
        overflow-y: hidden;
        position: relative;
        &::-webkit-scrollbar {
          display: none;
        }
      }
      li {
        width: 20%;
        text-align: center;
        box-sizing: border-box;
      }
    }
    .slide{
      height: .08rem;
      background:#fff;
      width:100%;
      padding: 0.04rem 0 0.08rem 0;
    }
    .slide .slide-bar{
      width: 40px;
      bottom: 2px;
      margin: 0 auto;
      height: .08rem;
      background:#f0f0f0;
      border-radius: .08rem;
    }
    .slide .slide-bar .slide-show{
      height:100%;
      border-radius: .08rem;
      background-color: #d2d2d2;
    }
    }

DDD7
265 声望5 粉丝

幻想某一天顶替产品经理的前端妹砸(>V