……

js 默认展示两行多余隐藏滑动及添加滑动条

Posted on 2023-12-08 15:51  WALL*E  阅读(54)  评论(0编辑  收藏  举报
<div class="nav-box" @scroll="scroll">
  <div for="list" class="nav">
    <div class="item-box">item</div>
  </div>
</div>
<div class="scroll-box" v-show="list.length/2 > 2">
  <div class="scroll" :style="'transform: translateX('+sX+')'"></div>
</div>
data() {
  return {
    sX: 0, //等比偏移量
    c_W: 0, //最外围容器宽度
    s_b_W: 0, //自定义滚动条盒子宽度
    s_W: 0, //自定义滚动条移动盒子宽度
    list:[],
  };
},
methods: {
  scroll(e) {
    let {
      sX,
      s_b_W,
      s_W,
      c_W,
      list
    } = this.$data

    let nW = e.target.scrollWidth // 得到scroll-view的总宽度
    let nwl = nW / (list / 2) //得到单个item的宽度
    let itemCount = c_W/nwl //得到显示的item数量
    let l = (list - (itemCount * 2)) / 2 //算出隐藏了多少item
    let nX = e.target.scrollLeft // 得到滑动的偏移量
    let sW = s_b_W - s_W + 2 //总宽度减去滑块的宽度,得出剩下的宽度,+2是为了去掉
    sX = sW / ((nwl * l) / nX) / 2 + 'px' // 最终得出等比偏移量
    this.sX = sX
  },
},
mounted() {
  this.c_W = document.getElementByClassName('nav-box')[0].offsetWidth
  this.s_b_W =  document.getElementByClassName('scroll-box')[0].offsetWidth
  this.s_W = document.getElementByClassName('scroll')[0].offsetWidth
}
.nav-box{
  overflow-x: scroll;
}
.nav{
  display: grid;
  grid-auto-flow: column;
  grid-template-rows: repeat(2, 1fr);
}
.item-box{
  width:81px;
}
.scroll-box {
  width: 70rpx;
  height: 10rpx;
  background: #f5e6e6;
  border-radius: 5rpx;
  margin: 24rpx auto 0;
}
.scroll {
  width: 30rpx;
  height: 100%;
  background: #efab67;
  border-radius: 5rpx;
}

效果展示:
image