先來看效果:
要求:頂部導航欄要始終固定在上方,不隨頁面上下拖動而消失。
代碼實現:
1.定義一個自定義導航欄組件:custom-nav-bar.vue,并寫入如下代碼:
<template><view class="layout"><view class="navBar"><view class="statusBar"></view><view class="titleBar"><view class="title">標題</view><view class="search"><uni-icons class="icon" type="search" color="#888" size="18"></uni-icons><text class="text">搜索</text></view></view></view><view class="fill"></view></view>
</template>
上面的代碼定義了狀態欄,標題欄的布局,其中:
1.狀態欄主要顯示時間、手機剩余電量等信息;
2.標題欄:實現搜索框,標題的效果。
CSS代碼:
<style lang="scss">.layout{.navBar{position: fixed;top:0;left: 0;width: 100%;z-index: 10;background:linear-gradient(to bottom,transparent,#fff 400rpx ),linear-gradient(to right,#beecd8 20%,#F4E2d8);.statusBar{}.titleBar{display: flex;padding: 0 30rpx;align-items: center;.title{font-size: 32rpx;font-weight: 700;color:$text-font-color-1;}.search{width: 220rpx;height: 50rpx;border-radius: 60rpx;background: rgba(255,255,255,0.4);border: 1px solid #fff;margin-left: 30rpx;color:#999;font-size: 28rpx;display: flex;align-items: center;.icon{margin-left: 5rpx;}.text{padding-left: 10rpx;}}}} }
</style>
CSS代碼知識概要:
1、固定定位 (position: fixed)
導航欄會脫離文檔流,始終固定在瀏覽器窗口的指定位置,不隨頁面滾動而移動。
2、緊貼頂部和左側 (top: 0; left: 0)
導航欄會固定在瀏覽器窗口的最頂部(top: 0),并且從最左側開始布局(left: 0)。
3、全寬度 (width: 100%)
導航欄會橫向撐滿整個屏幕寬度,覆蓋整個視窗的頂部區域。
4、層級較高 (z-index: 10)
導航欄會顯示在普通元素(z-index 默認是 auto 或 0)的上方,確保它不會被其他內容遮擋,同時可以覆蓋下方的滾動內容。
實際應用場景:
適用于網頁的頂部導航欄(如菜單欄、搜索欄、標題欄等)。常見于移動端或單頁應用(SPA),確保導航始終可見,方便用戶操作。
通常配合 padding-top 或 margin-top 給頁面主體內容留出空間,避免被導航欄遮擋。