在web开发过程中经常会碰到需要选择日期的功能,一般的操作都是在文本框点击,然后弹出日历选择框,直接选择日期就可以在文本框显示选择的日期。开发好之后给用户使用是很方便,但如果每一个日历选择器都要临时开发的话,会严重影响项目进度。所以网上有很多日历插件提供下载使用。
在实际工作中,日历选择器功能确实都是直接使用已开发好的插件。但作为一个前端工程师,还是需要知道具体实例方法,也应该有能力完成此类功能。本实例教程详细讲解怎么样使用原生js,通过面向对象来开发一个日历选择器插件。
一般日历插件使用都非常简单,只需要提供一个input元素就行,其他的工作都是通过插件来完成。本实例也先准备一个input元素待用,如下所示:
<div style="text-align:center;">
<input type="text" id="calendarInput">
</div>
原代码可以在《原生js日历选择器插件》下载。
接下来开始封装日历选择器插件。新建 calendar.js 文件,接下来的插件代码都写在此文件中。
需要在body元素中引入 calendar.js 文件,如下所示:
<script src="js/calendar.js"></ script>
把日历选择器功能拆分成一个一个的步骤来完成。
- 声明一个日历选择器插件的构造函数,可以传入input元素和配置选项两个参数,如下所示:
//创建日历插件构造函数
function CalendarPlugin(elem,opt={
}){
}
创建好这个函数之后,先在html文件中调用,这样可以在开发的过程中随时查看效果,如下所示:
<script src="js/calendar.js"></script>
<script>
//获取文本框
var eCalendarInput = document.getElementById('calendarInput');
//配置选项
var oConfig = {
}
//调用日历构造函数生成实例对象
var oCalenderObj = new CalendarPlugin(eCalendarInput,oConfig);
</script>
- 在构造函数的原型对象上创建init方法,并在构造函数中调用,如下所示:
//创建日历插件构造函数
function CalendarPlugin(elem,opt={
}){
//执行初始化
this.init();
}
//初始化
CalendarPlugin.prototype.init = function(){
}
- 创建日历插件所需要有元素
日历插件包括的元素比较多,开发过程中不要急,按照步骤,从上至下一个一个生成元素。
3.1 创建包裹和input容器等元素,把原文本框移到包裹元素中,并将包裹放到原父元素中,如下所示:
//创建日历插件构造函数
function CalendarPlugin(elem,opt={
}){
//把文本框设置为日历对象的属性
this.eInput = elem;
/*...*/
}
//初始化
CalendarPlugin.prototype.init = function(){
//获取原有intpu元素的父元素
var eInputParent = this.eInput.parentNode;
//创建日历包裹元素并添加class名称
var eWrap = document.createElement('div');
eWrap.className = 'calendar_wrap';
//创建文本框容器元素
var eInputContainer = document.createElement('div');
eInputContainer.className = 'calendar_container';
//创建清除按钮
var eClear = document.createElement('div');
eClear.className = 'calendar_clean';
//创建日历图标元素
var eIcon = document.createElement('div');
eIcon.className = 'calendar_icon';
//把日历包裹放到原有父元素中
eInputParent.appendChild(eWrap);
//文本框容器放到包裹中
eWrap.appendChild(eInputContainer);
//把相关元素放到文本框容器中
eInputContainer.appendChild(this.eInput);
eInputContainer.appendChild(eClear);
eInputContainer.appendChild(eIcon);
//设置文本框为只读
this.eInput.setAttribute('readonly',true);
}
此时文本框已经变成日历选择器的样式了,如图所示:
3.2 在init方法中创建弹出日历选择框元素
CalendarPlugin.prototype.init = function(){
/*...*/
//创建主要日历容器元素
this.eMain = document.createElement('div');
this.eMain.className = 'calendar_main';
//把日历容器放到包裹元素中
eWrap.appendChild(this.eMain);
}
3.3 在日历选择框中添加头部元素、主体元素和底部元素,代码如下:
CalendarPlugin.prototype.init = function(){
/*...*/
//创建日历头部
this.eHead = document.createElement('div');
this.eHead.className = 'calendar_head';
//把日历头部放到日历容器中
this.eMain.appendChild(this.eHead);
//设置当前年份
this.nYear = null;
//设置当前月份
this.nMonth = null;
//设置日历模式,默认显示日历
this.sModel = 'date';
//创建日历主体
this.eBody = document.createElement('div'<