技术研讨
2026-02-25
技术研讨
0
请注意,本文编写于 98 天前,最后修改于 98 天前,其中某些信息可能已经过时。

今天在使用uni-app开发微信小程序时,需要写一个横向导航栏,于是参考了京东微信小程序的样式,还原了它的效果,下面是简化后的代码。

这是一个可横向滚动的导航栏,选中某个导航项后,它会自动滚动到可视区域的第二个位置(即左侧保留一个前置项)。

参考来源: 京东微信小程序的横向导航设计

image.png

实现效果

image.png

代码中 systemInfoStore.menuButton.height 替换为导航栏的高度

vue
<template> <view class="nav-wrapper" :style="{ height: systemInfoStore.menuButton.height + 'px' }" > <!-- 左侧导航 --> <view class="nav-left"> <scroll-view class="nav-scroll" scroll-x :scroll-left="scrollLeft" scroll-with-animation > <view class="nav-item" :class="{ active: currentIndex === index }" v-for="(item, index) in navList" :key="index" @click="changeTab(index)" > {{ item }} </view> </scroll-view> </view> <!-- 右侧更多 --> <view class="nav-right" @click="handleMore"> <span class="iconfont icon-zhankai"></span> </view> </view> </template> <script setup> import { ref } from "vue"; import { SystemInfoStore } from "@/stores"; const systemInfoStore = SystemInfoStore(); const currentIndex = ref(0); const scrollLeft = ref(0); // 每个 tab 宽度(必须和 css 保持一致) const itemWidth = 55; const navList = ref([ "推荐", "风景", "美女", "动漫", "科技", "游戏", "汽车", "生活", "体育", "推荐", "风景", "美女", "动漫", "科技", "游戏", "汽车", "生活", "体育", "推荐", "风景", "美女", "动漫", "科技", "游戏", "汽车", "生活", "体育", ]); const changeTab = (index) => { currentIndex.value = index; // 当前项滑到第二个位置 const targetIndex = index - 1 < 0 ? 0 : index - 1; scrollLeft.value = targetIndex * itemWidth; }; const handleMore = () => { console.log("展开更多"); }; </script> <style lang="scss" scoped> .nav-wrapper { display: flex; align-items: center; width: 95%; margin: 0 auto; } .nav-left { flex: 1; overflow: hidden; } .nav-scroll { width: 100%; white-space: nowrap; } .nav-item { display: inline-block; width: 55px; /* 必须和 itemWidth 对应 */ text-align: left; font-size: 15px; color: var(--text-primary); } /* 激活状态 */ .active { color: var(--primary-color); font-weight: bold; } .nav-right { width: 35px; display: flex; align-items: center; justify-content: flex-end; background: var(---bg-secondary); border-left: 1px solid var(--bg-card); color: var(--text-primary); flex-shrink: 0; /* 防止被压缩 */ position: relative; } .nav-right::before { content: ""; position: absolute; left: 8px; top: 0; bottom: 0; width: 2px; background: linear-gradient(to right, rgba(0, 0, 0, 0.15), transparent); } </style>
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:猪聪聪

联系邮箱::[email protected]

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!