Pikaday.js简约轻量级的日期选择插件
Pikaday.js 是一个 JavaScript 日期选择器,它不依赖于任何第三方 JavaScript 库,并且文件大小小于 5K,但是功能却一点不弱,可以进行很多高级定制。并且样式可以根据 CSS 进行更改选择器的设计,当然默认的样式已经非常不错了。
特点
- 重量轻插件(小于5kb压缩和gzip)
- 没有依赖(如果需要格式化日期,可能需要使用到 Moment.js)
- 模块化CSS类,方便自定义样式。
使用方法
首先创建如下的输入框:
<input type="text" id="datepicker">
在页脚加载 Pikaday 的 JavaScript 库和 CSS 文件,并调用 Pikaday:
<link rel="stylesheet" href="pikaday.css">
<script src="pikaday.js"></script>
<script>
var picker = new Pikaday({ field: document.getElementById('datepicker') });
</script>
如果网页已经加载了 jQuery 库,其中调用代码可以改成下面更简洁的方式:
var picker = new Pikaday({ field: $('#datepicker')[0] });
如果pikaday实例未绑定到任何一个元素,你可以添加元素到任何地方:
var field = document.getElementById('datepicker');
var picker = new Pikaday({
onSelect: function(date) {
field.value = picker.toString();
}
});
field.parentNode.insertBefore(picker.el, field.nextSibling);
通过 Moment.js 高级格式化Pikaday.js日期的显示格式,你可以点击这里查看更多 Moment.js 的示例。
<input type="text" id="datepicker" value="9 Oct 2014">
<script src="moment.js"></script>
<script src="pikaday.js"></script>
<script>
var picker = new Pikaday({
field: document.getElementById('datepicker'),
format: 'D MMM YYYY',
onSelect: function() {
console.log(this.getMoment().format('Do MMMM YYYY'));
}
});
</script>
配置参数
As the examples demonstrate above Pikaday has many useful options:
field
bind the datepicker to a form fieldtrigger
use a different element to trigger opening the datepicker, see trigger example (default tofield
)bound
automatically show/hide the datepicker onfield
focus (defaulttrue
iffield
is set)position
preferred position of the datepicker relative to the form field, e.g.:top right
,bottom right
Note: automatic adjustment may occur to avoid datepicker from being displayed outside the viewport, see positions example (default to 'bottom left')reposition
can be set to false to not reposition datepicker within the viewport, forcing it to take the configuredposition
(default: true)container
DOM node to render calendar into, see container example (default: undefined)format
the default output format for.toString()
andfield
value (requires Moment.js for custom formatting)formatStrict
the default flag for moment's strict date parsing (requires Moment.js for custom formatting)defaultDate
the initial date to view when first openedsetDefaultDate
make thedefaultDate
the initial selected valuefirstDay
first day of the week (0: Sunday, 1: Monday, etc)minDate
the minimum/earliest date that can be selected (this should be a native Date object - e.g.new Date()
ormoment().toDate()
)maxDate
the maximum/latest date that can be selected (this should be a native Date object - e.g.new Date()
ormoment().toDate()
)disableWeekends
disallow selection of Saturdays or SundaysdisableDayFn
callback function that gets passed a Date object for each day in view. Should return true to disable selection of that day.yearRange
number of years either side (e.g.10
) or array of upper/lower range (e.g.[1900,2015]
)showWeekNumber
show the ISO week number at the head of the row (defaultfalse
)pickWholeWeek
select a whole week instead of a day (defaultfalse
)isRTL
reverse the calendar for right-to-left languagesi18n
language defaults for month and weekday names (see internationalization below)yearSuffix
additional text to append to the year in the titleshowMonthAfterYear
render the month after year in the title (defaultfalse
)showDaysInNextAndPreviousMonths
render days of the calendar grid that fall in the next or previous months to the current month instead of rendering an empty table cell (default: false)numberOfMonths
number of visible calendarsmainCalendar
whennumberOfMonths
is used, this will help you to choose where the main calendar will be (defaultleft
, can be set toright
). Only used for the first display or when a selected date is not already visibleevents
array of dates that you would like to differentiate from regular days (e.g.['Sat Jun 28 2017', 'Sun Jun 29 2017', 'Tue Jul 01 2017',]
)theme
define a classname that can be used as a hook for styling different themes, see theme example (defaultnull
)blurFieldOnSelect
defines if the field is blurred when a date is selected (defaulttrue
)onSelect
callback function for when a date is selectedonOpen
callback function for when the picker becomes visibleonClose
callback function for when the picker is hiddenonDraw
callback function for when the picker draws a new month
jQuery Plugin
The normal version of Pikaday does not require jQuery, however there is a jQuery plugin if that floats your boat (see plugins/pikaday.jquery.js
in the repository). This version requires jQuery, naturally, and can be used like other plugins: See the jQuery example for a full version.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="pikaday.js"></script>
<script src="plugins/pikaday.jquery.js"></script>
<script>
// activate datepickers for all elements with a class of `datepicker`
$('.datepicker').pikaday({ firstDay: 1 });
// chain a few methods for the first datepicker, jQuery style!
$('.datepicker').eq(0).pikaday('show').pikaday('gotoYear', 2042);
</script>
AMD support
If you use a modular script loader than Pikaday is not bound to the global object and will fit nicely in your build process. You can require Pikaday just like any other module. See the AMD example for a full version.
require(['pikaday'], function(Pikaday) {
var picker = new Pikaday({ field: document.getElementById('datepicker') });
});
The same applies for the jQuery plugin mentioned above. See the jQuery AMD example for a full version.
require(['jquery', 'pikaday.jquery'], function($) {
$('#datepicker').pikaday();
});
CommonJS module support
If you use a CommonJS compatible environment you can use the require function to import Pikaday.
var pikaday = require('pikaday');
When you bundle all your required modules with Browserify and you don't use Moment.js specify the ignore option:
browserify main.js -o bundle.js -i moment
Ruby on Rails
If you're using Ruby on Rails, make sure to check out the Pikaday gem.
Methods
You can control the date picker after creation:
var picker = new Pikaday({ field: document.getElementById('datepicker') });
Get and set date
picker.toString('YYYY-MM-DD')
Returns the selected date in a string format. If Moment.js exists (recommended) then Pikaday can return any format that Moment understands, otherwise you're stuck with JavaScript's default.
picker.getDate()
Returns a basic JavaScript Date
object of the selected day, or null
if no selection.
picker.setDate('2015-01-01')
Set the current selection. This will be restricted within the bounds of minDate
and maxDate
options if they're specified. You can optionally pass a boolean as the second parameter to prevent triggering of the onSelect callback (true), allowing the date to be set silently.
picker.getMoment()
Returns a Moment.js object for the selected date (Moment must be loaded before Pikaday).
picker.setMoment(moment('14th February 2014', 'DDo MMMM YYYY'))
Set the current selection with a Moment.js object (see setDate
for details).
Change current view
picker.gotoDate(new Date(2014, 1))
Change the current view to see a specific date. This example will jump to February 2014 (month is a zero-based index).
picker.gotoToday()
Shortcut for picker.gotoDate(new Date())
picker.gotoMonth(2)
Change the current view by month (0: January, 1: Februrary, etc).
picker.nextMonth()
picker.prevMonth()
Go to the next or previous month (this will change year if necessary).
picker.gotoYear()
Change the year being viewed.
picker.setMinDate()
Update the minimum/earliest date that can be selected.
picker.setMaxDate()
Update the maximum/latest date that can be selected.
picker.setStartRange()
Update the range start date. For using two Pikaday instances to select a date range.
picker.setEndRange()
Update the range end date. For using two Pikaday instances to select a date range.
Show and hide datepicker
picker.isVisible()
Returns true
or false
.
picker.show()
Make the picker visible.
picker.adjustPosition()
Recalculate and change the position of the picker.
picker.hide()
Hide the picker making it invisible.
picker.destroy()
Hide the picker and remove all event listeners — no going back!
Internationalization
The default i18n
configuration format looks like this:
i18n: {
previousMonth : 'Previous Month',
nextMonth : 'Next Month',
months : ['January','February','March','April','May','June','July','August','September','October','November','December'],
weekdays : ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
weekdaysShort : ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
}
You must provide 12 months and 7 weekdays (with abbreviations). Always specify weekdays in this order with Sunday first. You can change the firstDay
option to reorder if necessary (0: Sunday, 1: Monday, etc). You can also set isRTL
to true
for languages that are read right-to-left.
浏览器兼容
- IE 7+
- Chrome 8+
- Firefox 3.5+
- Safari 3+
- Opera 10.6+
相关链接
- Github地址:https://github.com/dbushell/Pikaday
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论