小程序 顶部区域弹出picker的下拉框代码
时间: 2024-05-12 10:13:46 浏览: 50
以下是小程序中顶部区域弹出picker的下拉框代码示例:
WXML部分:
```html
<view class="container">
<view class="picker">
<view class="picker-btn" bindtap="showPicker">
<text>{{selectedValue}}</text>
<image src="/images/down.png"></image>
</view>
<picker class="picker-box" value="{{selectedIndex}}" range="{{pickerData}}" bindchange="pickerChange" bindcancel="hidePicker">
<view class="picker-item">{{pickerData[selectedIndex]}}</view>
</picker>
</view>
</view>
```
CSS部分:
```css
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.picker {
position: relative;
width: 200rpx;
height: 50rpx;
border: 1rpx solid #ccc;
border-radius: 5rpx;
background-color: #fff;
}
.picker-btn {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 10rpx;
height: 100%;
}
.picker-btn image {
width: 20rpx;
height: 20rpx;
}
.picker-box {
position: absolute;
top: 50rpx;
left: 0;
width: 100%;
background-color: #fff;
z-index: 10;
}
.picker-item {
text-align: center;
font-size: 14rpx;
padding: 10rpx;
line-height: 1.5;
color: #333;
border-top: 1rpx solid #ccc;
}
```
JS部分:
```javascript
Page({
data: {
pickerData: ['选项1', '选项2', '选项3', '选项4'],
selectedIndex: 0,
selectedValue: '选项1',
isPickerShow: false
},
showPicker() {
this.setData({
isPickerShow: true
});
},
hidePicker() {
this.setData({
isPickerShow: false
});
},
pickerChange(e) {
const selectedIndex = e.detail.value;
const selectedValue = this.data.pickerData[selectedIndex];
this.setData({
selectedIndex,
selectedValue,
isPickerShow: false
});
}
})
```
在上面的代码中,我们首先定义了一个picker组件,然后在picker-box里面定义了picker-item,用来展示每个选项。在picker-btn中,我们绑定了一个showPicker事件,点击该按钮时,会显示picker-box,选择完成后,我们监听了picker的change事件,获取选中的值,并更新selectedValue的值,然后再将picker-box隐藏起来。
阅读全文