小程序開發過程中有選身高的功能,用了picker-view。官方文檔說indicator-style和indicator-class是設定選中框的樣式和類名。我用的是uni-app框架。

然后就設置了上下邊框顏色以及字體顏色,但是發現字體顏色並沒有效果,代碼如下:
html部分:
<view class="selectPicker"> <picker-view class="picker" indicator-class="picker-box" indicator-style="height:80upx;" :value="value" @change="bindChange"> <picker-view-column class="item"> <view class="text" v-for="(item,index) in heights" :key="index">{{item}} cm</view> </picker-view-column> </picker-view> </view>
JS部分:
const heights = [] for (let i = 100; i<= 230; i++) { heights.push(i) } export default { data: function () { return { title: 'picker-view', heights:heights, height:165, value:[65] } }, methods: { bindChange: function (e) { const val = e.detail.value this.value = val this.height = this.heights[val[0]] console.log(this.height) } } }
CSS部分:
.picker-box{ width:100%; border-top:3upx solid #4CD964; border-bottom:3upx solid #4CD964; color: #4CD964; }
效果圖如下:

后來網上查了,大家都是設置不了,於是就用索引來給選中框選中樣式。但是遇到了一個坑,一開始我是為了省幾行代碼,直接使用:style來添加樣式。
<view class="selectPicker"> <picker-view class="picker" indicator-class="picker-box" indicator-style="height:80upx;" :value="value" @change="bindChange"> <picker-view-column class="item"> <view :style="value[0]==index?'color:#4CD964;':''" class="text" v-for="(item,index) in heights" :key="index">{{item}} cm</view> </picker-view-column> </picker-view> </view>
value(是個數組形式,所以需要value[0])的值官方文檔介紹了是選中框的索引,一旦滾動就會觸發change事件,value的值就會變成選中框的索引。所以用value[0]的值和index來比較是否相等。相等則會增加樣式color。這樣寫,出現了個bug,就是選中框的value和選中框的值不對應。如下圖:是我拍的視頻然后截圖,不是很清晰。
明明選的是1948,但是選中框顯示的是1948和1949之間的內容,越往下滑,越明顯。

然后就改了,用class動態名來綁定樣式,發現字體顏色最終改變了。代碼如下:
HTML:
<view class="selectPicker"> <picker-view class="picker" indicator-class="picker-box" indicator-style="height:80upx;" :value="value" @change="bindChange"> <picker-view-column class="item"> <view :class="value[0]==index?'pickerSelected':''" class="text" v-for="(item,index) in heights" :key="index">{{item}} cm</view> </picker-view-column> </picker-view> </view>
增加的CSS代碼:
.pickerSelected{ color: #4CD964; }
