uniapp cover-view做一个左右滚动的导航栏,不要用scroll-view

<template>
  <view class="container">
    <cover-view class="nav-container" 
                @touchstart="touchStart" 
                @touchmove="touchMove"
                @touchend="touchEnd">
      <cover-view class="nav-content" :style="{ transform: `translateX(${offsetX}px)` }">
         <cover-view
            v-for="(item, index) in navList"
            :key="index"
            class="nav-item"
            :class="{ active: currentIndex === index }"
            @click="handleClick(index)"
          >
            {{ item }}
          </cover-view>
      </cover-view>
    </cover-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      navList: ['首页', '推荐', '热门', '科技', '体育', '财经', '娱乐', '时尚'],
      currentIndex: 0,
      moveX: 0,
      containerWidth: 0, // 容器宽度
      contentWidth: 0, // 内容总宽度
      offsetX: 0, // 当前偏移
      startX: 0, // 触摸起点
    };
  },
  onReady() {
    this.calculateWidths();
  },
  methods: {
    // 获取容器和内容宽度
    calculateWidths() {
      const query = uni.createSelectorQuery().in(this);
      query.select('.nav-container').boundingClientRect(res => {
        this.containerWidth = res.width;
      }).exec();
      
      query.select('.nav-content').boundingClientRect(res => {
        this.contentWidth = res.width;
      }).exec();
    },
    
    touchStart(e) {
      this.startX = e.touches[0].pageX;
    },
    
    touchMove(e) {
      const moveX = e.touches[0].pageX - this.startX;
      const newOffset = this.offsetX + moveX;
      const maxOffset = -(this.contentWidth - this.containerWidth);
      
      // 边界检测
      this.offsetX = Math.max(Math.min(newOffset, 0), maxOffset);
      this.startX = e.touches[0].pageX;
    },
    
    // 触摸释放时确保在边界内
    touchEnd() {
      if (this.offsetX > 0) this.offsetX = 0;
      if (this.offsetX < -(this.contentWidth - this.containerWidth)) {
        this.offsetX = -(this.contentWidth - this.containerWidth);
      }
    }
  }
};
</script>

<style>
.nav-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    white-space: nowrap;
    position: relative;
  }
  .nav-content {
    display: inline-block;
    height: 100%;
    transition: transform 0.3s cubic-bezier(0.1, 0.57, 0.1, 1);
  }
  .nav-item {
    display: inline-block;
    padding: 0 30rpx;
    height: 100%;
    line-height: 80rpx;
    font-size: 28rpx;
    color: #666;
    position: relative;
  }
  .nav-item.active {
    color: #007aff;
    font-weight: bold;
  }
  .nav-item.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 40rpx;
    height: 4rpx;
    background-color: #007aff;
    border-radius: 2rpx;
  }
</style>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容