picker滚动选择器(下简称picker)是微信小程序自带的组件,无需引入任何文件,只要在适当的位置放入picker代码点击后就可以从底部弹起的滚动选择器。我们接下来就要实现类似的功能,做到我们自己的需求.
功能要求:
- 实现列表的滚动,列表中间的元素边框颜色加重.
- 滚动的时候默认选中间位置的元素
- 点确定选中并打印出来,
- 等等等功能 ,具体你们自己去看吧
首先我们搭建一下页面结构.
html
<template>
<view class="container">
<button @tap="showModal = !showModal">显示</button>
<view v-if="showModal" class="modal">
<view class="content">
<scroll-view class="picker" scroll-y="true" @scroll="onScroll">
<view class="picker-spacer"></view>
<view v-for="(item, i) in array" :key="i" class="picker-item aaa" :class="{ 'picker-item-selected': selectedIndex === i }">
{{ item }}
</view>
<view class="picker-spacer"></view>
</scroll-view>
<view class="picker-highlight"></view>
<view class="buttons">
<button class="qv" @click="cancel">取消</button>
<button class="qd" @click="confirm">确定</button>
</view>
</view>
</view>
</view>
</template>
接下来我们定义一下css
<style lang="scss">
.container {
width: 100%;
}
.modal {
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.content {
position: fixed;
bottom: 90upx;
width: 100%;
background-color: white;
}
.picker {
position: relative;
height: 200px;
overflow: scroll;
}
.picker-item {
height: 40px;
line-height: 40px;
text-align: center;
}
.aaa {
border-top: 1px solid #f8f8f8;
border-bottom: 1px solid #f8f8f8;
}
.picker-item-selected {
width: 100%;
border-top: 1px solid #b0b0b0;
border-bottom: 1px solid #b0b0b0;
}
.picker-spacer {
height: 80px;
}
.picker-highlight {
position: absolute;
top: 80px;
width: 100%;
height: 40px;
// border-top: 1px solid black;
// border-bottom: 1px solid black;
pointer-events: none;
}
.buttons {
display: flex;
justify-content: space-between;
}
.qv {
text-align: center;
line-height: 80upx;
height: 80upx;
width: 180upx;
background-color: #b0b0b0;
}
.qd {
text-align: center;
line-height: 80upx;
height: 80upx;
width: 180upx;
background-color: rgba(198, 150, 79, 1);
}
</style>
逻辑部分
<script>
export default {
data() {
return {
showModal: false,
array: ['选项1', '选项2', '选项3', '选项4', '选项5', '选项6'],
selectedIndex: 0
};
},
methods: {
onScroll(e) {
const itemHeight = 40;
this.selectedIndex = Math.round(e.target.scrollTop / itemHeight);
},
cancel() {
this.showModal = false;
},
confirm() {
this.showModal = false;
console.log('你选择了:' + this.array[this.selectedIndex]);
}
}
};
</script>
直接复制代码就能用 不用谢我,个人瞎写的