首页
/ AirDatepicker 日期选择器核心功能与高级用法详解

AirDatepicker 日期选择器核心功能与高级用法详解

2025-07-10 07:02:33作者:郜逊炳

一、AirDatepicker 简介

AirDatepicker 是一个轻量级、高度可定制的日期选择器组件,适用于现代 Web 应用开发。它提供了丰富的日期选择功能,包括单日选择、日期范围选择、时间选择等,并支持多种自定义选项。

二、基础安装与使用

1. 安装方式

通过 npm 可以轻松安装 AirDatepicker:

npm i air-datepicker -S

2. 基础引入

在项目中引入 AirDatepicker 及其样式:

import AirDatepicker from 'air-datepicker';
import 'air-datepicker/air-datepicker.css';

3. 基本初始化

最简单的初始化方式只需要指定目标元素:

new AirDatepicker('#input');

三、核心功能详解

1. 内联模式

AirDatepicker 支持两种内联模式:

// 直接在div元素上初始化
new AirDatepicker('#div');

// 在input元素上使用inline选项
new AirDatepicker('#input', {
    inline: true
})

2. 默认选中日期

可以设置初始选中的日期:

new AirDatepicker('#el', {
    selectedDates: [new Date()]  // 默认选中当天
})

3. 视图控制

通过 viewminView 可以控制显示的视图层级:

new AirDatepicker('#el', {
    view: 'months',      // 初始显示月份视图
    minView: 'months',   // 最小显示到月份视图
    dateFormat: 'MMMM yyyy'  // 日期格式
})

四、高级功能实现

1. 日期范围选择

实现日期范围选择功能:

new AirDatepicker('#input', {
    range: true,  // 启用范围选择
    multipleDatesSeparator: ' - '  // 日期分隔符
});

2. 范围限制

实现两个日期选择器之间的最小/最大日期限制:

let dpMin, dpMax;

dpMin = new AirDatepicker('#el1', {
    onSelect({date}) {
        dpMax.update({
            minDate: date  // 设置第二个选择器的最小日期
        })
    }
})

dpMax = new AirDatepicker('#el2', {
    onSelect({date}) {
        dpMin.update({
            maxDate: date  // 设置第一个选择器的最大日期
        })
    }
})

3. 时间选择

启用时间选择功能:

new AirDatepicker('#input', {
    timepicker: true,  // 启用时间选择
    timeFormat: 'hh:mm AA'  // 时间格式
});

五、自定义功能实现

1. 自定义单元格内容

可以完全自定义日期单元格的显示内容和样式:

let today = new Date();

new AirDatepicker('#inline-div', {
    onRenderCell({date, cellType}) {
        let dates = [1, 5, 7, 10, 15, 20, 25],
            emoji = ['💕', '😃', '🍙', '🍣', '🍻', '🎉', '🥁'],
            isDay = cellType === 'day',
            _date = date.getDate(),
            shouldChangeContent = isDay && dates.includes(_date),
            randomEmoji = emoji[Math.floor(Math.random() * emoji.length)];
    
        return {
            html: shouldChangeContent ? randomEmoji : undefined,
            classes: shouldChangeContent ? '-emoji-cell-' : undefined,
            attrs: {
                title: shouldChangeContent ? randomEmoji : ''
            }
        }
    },
    selectedDates: new Date(today.getFullYear(), today.getMonth(), 10)
});

配合自定义CSS样式:

.-emoji-cell- {
    --adp-cell-background-color-selected: #ffb8ff;
    --adp-cell-background-color-selected-hover: #fda5fd;
}

2. 自定义标题

可以自定义导航标题的显示内容:

new AirDatepicker('#el', {
    navTitles: {
        days: '<strong>yyyy</strong> <i>MMMM</i>',
        months: 'Select month of <strong>yyyy</strong>'    
    }
})

3. 自定义按钮

AirDatepicker 支持添加自定义按钮:

new AirDatepicker('#el', {
    buttons: ['today', 'clear']  // 内置按钮
});

// 高级自定义按钮
new AirDatepicker('#el', {
    buttons: [
        {
            content(dp) {
                return dp.opts.timepicker 
                    ? '关闭时间选择'
                    : '开启时间选择'
            },
            onClick(dp) {
                let viewDate = dp.viewDate;
                let today = new Date();
                
                viewDate.setHours(today.getHours());
                viewDate.setMinutes(today.getMinutes());

                dp.update({
                    timepicker: !dp.opts.timepicker,
                    viewDate
                })
            }
        }
    ]
})

六、高级定位控制

1. 基本定位

new AirDatepicker('#el', {
    position: 'right center'  // 相对于目标元素的定位
})

2. 自定义定位回调

new AirDatepicker('#el', {
    autoClose: true,
    position({$datepicker, $target, $pointer}) {
        let coords = $target.getBoundingClientRect(),
            dpHeight = $datepicker.clientHeight,
            dpWidth = $datepicker.clientWidth;
    
        let top = coords.y + coords.height / 2 + window.scrollY - dpHeight / 2;
        let left = coords.x + coords.width / 2 - dpWidth / 2;
    
        $datepicker.style.left = `${left}px`;
        $datepicker.style.top = `${top}px`;
    
        $pointer.style.display = 'none';
    }
})

3. 使用Popper.js实现高级定位

import {createPopper} from '@popperjs/core';

new AirDatepicker('#el', {
    container: '#scroll-container',
    visible: true,
    position({$datepicker, $target, $pointer, done}) {
        let popper = createPopper($target, $datepicker, {
            placement: 'top',
            modifiers: [
                {
                    name: 'flip',
                    options: {
                        padding: {
                            top: 64
                        }
                    }
                },
                {
                    name: 'offset',
                    options: {
                        offset: [0, 20]
                    }
                },
                {
                    name: 'arrow',
                    options: {
                        element: $pointer
                    }
                }
            ]
        })
        
        return function completeHide() {
            popper.destroy();
            done();
        }    
    }
})

七、总结

AirDatepicker 提供了丰富的功能和灵活的定制选项,可以满足各种日期选择需求。从基本的日期选择到复杂的范围限制、自定义单元格内容和高级定位,开发者可以根据项目需求灵活配置。通过本文介绍的各种用法,您可以快速掌握 AirDatepicker 的核心功能并实现复杂的日期选择场景。