文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

js 实现picker 选择器示例详解

2022-11-13 18:19

关注

前言

想必各位做移动端开发的小伙伴对picker选择器应该不陌生吧。你做微信小程序开发有自带的picker组件,做公众号开发可以使用weui提供的picker组件。除此之外,市面上开源的picker组件也是层出不穷,拿来即用。但如果叫你自己实现一个,你会如何实现呢?我花了点时间写了一个简单的demo,希望能给想自己动手实现一个picker选择器但又无从下手的小伙伴提供一个思路。

实现

CSS

* {
    margin: 0;
    padding: 0;
}
.btn {
    height: 32px;
    padding: 0 15px;
    text-align: center;
    font-size: 14px;
    line-height: 32px;
    color: #FFF;
    border: none;
    background: #1890ff;
    border-radius: 2px;
    cursor: pointer;
}
.mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999;
    background: rgba(0, 0, 0, .6);
    animation: fadeIn .3s forwards;
}
.slide-box {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 15px;
    border-radius: 10px 10px 0 0;
    background: #FFF;
    user-select: none;
}
.fade-in {
    animation: fadeIn .3s forwards;
}
@keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}
.fade-out {
    animation: fadeOut .3s forwards;
}
@keyframes fadeOut {
    from {
        opacity: 10;
    }
    to {
        opacity: 0;
    }
}
.slide-up {
    animation: slideUp .3s forwards;
}
@keyframes slideUp {
    from {
        transform: translate3d(0, 100%, 0);
    }
    to {
        transform: translate3d(0, 0, 0);
    }
}
.slide-down {
    animation: slideDown .3s forwards;
}
@keyframes slideDown {
    from {
        transform: translate3d(0, 0, 0);
    }
    to {
        transform: translate3d(0, 100%, 0);
    }
}
h4 {
    height: 24px;
    margin-bottom: 16px;
    font-size: 16px;
    line-height: 24px;
    text-align: center;
}
.picker-group {
    display: flex;
}
.picker-column {
    position: relative;
    flex: 1;
    height: 200px;
    margin: 0 auto;
    overflow: hidden;
    touch-action: none;
}
.picker-column::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
    height: 79px;
    border-bottom: 1px solid #ebebeb;
    background: linear-gradient(to bottom, rgba(255, 255, 255, .9), rgba(255, 255, 255, .6));
}
.picker-column::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 1;
    height: 79px;
    border-top: 1px solid #ebebeb;
    background: linear-gradient(to bottom, rgba(255, 255, 255, .6), rgba(255, 255, 255, .9));
}
li {
    list-style: none;
    font-size: 14px;
    line-height: 40px;
    text-align: center;
}
.btn-sure {
    display: block;
    margin: 15px auto 0;
}

HTML

<button class="btn btn-open" type="button">时间选择器</button>
<div hidden class="mask">
    <div class="slide-box">
        <h4>时间选择器</h4>
        <div class="picker-group">
            <div class="picker-column">
                <ul class="picker-content"></ul>
            </div>
            <div class="picker-column">
                <ul class="picker-content"></ul>
            </div>
        </div>
        <button class="btn btn-sure" type="button">确定</button>
    </div>
</div>

js

class Picker {
    constructor(options) {
        this.options = Object.assign({}, options);
        this.isPointerdown = false;
        this.itemHeight = 40; // 列表项高度
        this.maxY = this.itemHeight * 2;
        this.minY = this.itemHeight * (3 - this.options.list.length);
        this.lastY = 0;
        this.diffY = 0;
        this.translateY = 0; // 当前位置
        this.friction = 0.95; // 摩擦系数
        this.distanceY = 0; // 滑动距离
        this.result = this.options.list[0];
        this.render();
        this.bindEventListener();
    }
    render() {
        let html = '';
        for (const item of this.options.list) {
            html += '<li>' + item + '</li>';
        }
        this.options.pickerContent.innerHTML = html;
        this.options.pickerContent.style.transform = 'translate3d(0px, ' + this.maxY + 'px, 0px)';
    }
    handlePointerdown(e) {
        // 如果是鼠标点击,只响应左键
        if (e.pointerType === 'mouse' && e.button !== 0) {
            return;
        }
        this.options.pickerColumn.setPointerCapture(e.pointerId);
        this.isPointerdown = true;
        this.lastY = e.clientY;
        this.diffY = 0;
        this.distanceY = 0;
        this.getTransform();
        this.options.pickerContent.style.transform = 'translate3d(0px, ' + this.translateY + 'px, 0px)';
        this.options.pickerContent.style.transition = 'none';
    }
    handlePointermove(e) {
        if (this.isPointerdown) {
            this.diffY = e.clientY - this.lastY;
            this.translateY += this.diffY;
            this.lastY = e.clientY;
            this.options.pickerContent.style.transform = 'translate3d(0px, ' + this.translateY + 'px, 0px)';
        }
    }
    handlePointerup(e) {
        if (this.isPointerdown) {
            this.isPointerdown = false;
            this.getTranslateY();
            // 滑动距离与时长成正比且最短时长为300ms
            const duration = Math.max(Math.abs(this.distanceY) * 1.5, 300);
            this.options.pickerContent.style.transition = 'transform ' + duration + 'ms ease';
            this.options.pickerContent.style.transform = 'translate3d(0px, ' + this.translateY + 'px, 0px)';
        }
    }
    handlePointercancel(e) {
        if (this.isPointerdown) {
            this.isPointerdown = false;
        }
    }
    bindEventListener() {
        this.handlePointerdown = this.handlePointerdown.bind(this);
        this.handlePointermove = this.handlePointermove.bind(this);
        this.handlePointerup = this.handlePointerup.bind(this);
        this.handlePointercancel = this.handlePointercancel.bind(this);
        this.options.pickerColumn.addEventListener('pointerdown', this.handlePointerdown);
        this.options.pickerColumn.addEventListener('pointermove', this.handlePointermove);
        this.options.pickerColumn.addEventListener('pointerup', this.handlePointerup);
        this.options.pickerColumn.addEventListener('pointercancel', this.handlePointercancel);
    }
    getTransform() {
        const transform = window.getComputedStyle(this.options.pickerContent).getPropertyValue('transform');
        this.translateY = parseFloat(transform.split(',')[5]);
    }
    getTranslateY() {
        let speed = this.diffY;
        while (Math.abs(speed) > 1) {
            speed *= this.friction;
            this.distanceY += speed;
        }
        // 边界判断
        let y = this.translateY + this.distanceY;
        if (y > this.maxY) {
            this.translateY = this.maxY;
            this.distanceY = this.maxY - this.translateY;
        } else if (y < this.minY) {
            this.translateY = this.minY;
            this.distanceY = this.minY - this.translateY;
        } else {
            this.translateY = y;
        }
        // 计算停止位置使其为itemHeight的整数倍
        let i = Math.round(this.translateY / this.itemHeight);
        this.translateY = i * this.itemHeight;
        this.result = this.options.list[2 - this.translateY / this.itemHeight];
    }
}
// 调用方式
function createList(start, end) {
    const list = [];
    for (i = start; i < end; i++) {
        list[i] = i < 10 ? '0' + i : '' + i;
    }
    return list;
}
const hours = createList(0, 24), minutes = createList(0, 60);
const pickerColumns = document.querySelectorAll('.picker-column');
const pickerContents = document.querySelectorAll('.picker-content');
const hourPicker = new Picker({
    pickerColumn: pickerColumns[0],
    pickerContent: pickerContents[0],
    list: hours
});
const minutePicker = new Picker({
    pickerColumn: pickerColumns[1],
    pickerContent: pickerContents[1],
    list: minutes
});

Demo:jsdemo.codeman.top/html/picker…

结语

至此,一个简单的picker选择器就实现了。如果小伙伴们想实现根据前一列选中项动态加载后一列数据的功能(例如省市区选择器)还需在此代码基础上自行实现。

以上就是js 实现picker 选择器示例详解的详细内容,更多关于js实现picker选择器的资料请关注编程网其它相关文章!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-前端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯