您好,登錄后才能下訂單哦!
這篇文章主要介紹js如何實現前端日歷控件,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
首先說下控件的依賴包,加載控件的時候必須先加載jQuery, jQuqery.UI, 另外jquery-ui.css
這個包也需要引用,此包主要應用了jQuery拖拽和放縮的樣式,控件樣式方面大家自由發揮,給了個自己寫的默認樣式包 (獻丑了)。
控件本身支持顏色自定義,可根據日期自定義日歷上某日的顏色,另外可懸浮,拖拽,自由變形算是賣點吧,哈哈
控件包加載是這樣的:
<link href="../../Content/themes/base/jquery-ui.css" rel="stylesheet" /> <link href="../../Content/datePrinter.css" rel="stylesheet" /> <script src="../../Scripts/default/jquery-ui-1.8.20.min.js"></script> <script src="../../Scripts/control/datePrinter.js"></script>
控件中的核心部分就是打印選中月的日歷,是參考網上的代碼,偷懶嘛,歡迎認領
例如頁面代碼如下:
<input type="text" id="datepickerInput"/>
調用的寫法:
var dpCon = $("#datepickerInput").datePrinter({ initDate: "2017-4-5", //初始化日期 language: "EN", //語言 resizable: true, //可自由變形 draggable: true, //可懸浮拖拽 showYearAndMonth: true, //是否顯示年月下拉框 getColor: getColor, //自定義顏色接口 chooseDone: chooseDone //選中日歷某日執行事件接口 }); //選中日期時讓日歷消失 當然此處可以執行比較復雜的業務,如服務器數據請求 function chooseDone(date) { dpCon.datePrinter("dpHide"); } //自定義日期顏色 function getColor(day){ if(day == 3 || day==7 || day==15) return "dpdisabled"; else if(day== 5 || day==18 || day==23) return "dpyellow"; else return "dpenable"; } //獲取當前選中的日期 調用控件提供的API getSelectDate dpCon.datePrinter("getSelectDate");
這樣子就給上面的input text控件注冊了一個日歷控件,在點擊input時,日歷就會浮出,效果如下
你可能注意到右下角的小三角了,鼠標放上去之后可以隨意變化日歷的長寬,另外在日歷上按住鼠標左鍵可以隨意移動日期控件的位置,不擠占頁面位置
下面這段是打印日歷的代碼,供參考:
//默認獲取當前日期 var today = option.initDate ? option.initDate : new Date(); this.options.initDate = today; //獲取日期中的年份 var y = today.getFullYear(), //獲取日期中的月份(需要注意的是:月份是從0開始計算,獲取的值比正常月份的值少1) m = today.getMonth(), //獲取日期中的日(方便在建立日期表格時高亮顯示當天) d = today.getDate(), //獲取當月的第一天 firstday = new Date(y, m, 1), //判斷第一天是星期幾(返回[0-6]中的一個,0代表星期天,1代表星期一,以此類推) dayOfWeek = firstday.getDay() == 0 ? 7 : firstday.getDay(), //創建月份數組 days_per_month = new Array(31, 28 + self._isLeap(y), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31), //確定日期表格所需的行數 str_nums = Math.ceil((dayOfWeek + days_per_month[m] - 1) / 7); //二維數組創建日期表格 for (i = 0; i < str_nums; i += 1) { var tr = '<tr>'; for (k = 0; k < 7; k++) { //為每個表格創建索引,從0開始 var idx = 7 * i + k; //將當月的1號與星期進行匹配 var day = idx - dayOfWeek +2; var styleName = self._getColor(day); if (option.getColor && typeof (option.getColor) == 'function') styleName = option.getColor(day); styleName += " dateTD"; (day <= 0 || day > days_per_month[m]) ? //索引小于等于0或者大于月份最大值就用空表格代替 (day = ' ', styleName = "dpBlank") : (day = idx - dayOfWeek + 2); day == d ? tr += '<td class="' + styleName + ' today">' + day + '</td>' : //高亮顯示當天 tr += '<td class="' + styleName + '">' + day + '</td>'; } tr += '</tr>'; self._dpTable.append(tr); tr = ""; }
以前都是寫后臺,玩前端的時間不長,有不對的地方歡迎指正
datePrinter.js的全部代碼如下:
var _datePrinter_tmpl_CN = "<tr><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th><th>日</th></tr>"; var _datePrinter_tmpl_EN = "<tr><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th><th>Sun</th></tr>"; Date.prototype.Format = function (fmt) { //author: meizz var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小時 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; } $.widget("ui.datePrinter", { options: { initDate: null, language: null, // CN,EN resizable: false, draggable: false, width: "240px", dateFormat:'yyyy/MM/dd', getColor: null, //自定義顏色 showYearAndMonth: false, chooseDone: function (selectDate) { return selectDate }, //選中日期后執行的自定義事件 autoId:null //控件Id }, _dpTable: null, _dpRoot:null, _selectDate:null, //選中日期 _create: function () { var self = this, option = this.options, ele = this.element; $(ele).after("<div class='dpRoot'></div>"); self._dpRoot = $(ele).parent().find('div.dpRoot'); self._dpRoot.empty(); self._dpRoot.append("<div class='dpTitle' style='text-align:right;background-color:#e8edf4; width:" + option.width + "'><select class='selYear'></select><select class='selMonth'></select><a style='color:#000;text-decoration:none;font-size:18px;padding-left:10px; padding-right:10px;width:10px;' href='javascript:void(0);'>x</a></div>"); self._dpRoot.append("<table style='width:" + option.width + "' cellspacing='0'></table>"); option.autoId = self._newGuid(); }, _init: function () { var self = this, option = this.options, ele = this.element; if (option.initDate && typeof option.initDate == 'string') option.initDate = new Date(option.initDate.replace("-", "/")); //初始化日歷 self._initDate(); //點擊事件 self._dpTable.delegate("td", "click", function () { if (!$(this).hasClass("dpBlank")) { self._dpTable.find("td").removeClass("today"); $(this).addClass("today"); //控件設置值 $.proxy(self._setDate($(this).text()), self); if (option.chooseDone && typeof (option.chooseDone) == 'function') $.proxy(option.chooseDone(self._selectDate), self); } }); if (option.resizable) self._dpRoot.resizable({ minHeight: self._dpRoot.css("height").replace("px",''), minWidth:option.width.replace("px",''), resize: function (event, ui) { var titleHeight = self._dpRoot.find("div.dpTitle").css("height").replace("px", ""); //最小值時不再縮小 if (ui.size.width >= Number(option.width.replace("px",''))) { $(ui.element).find("table").css({ "width": ui.size.width, "height": ui.size.height - titleHeight, "text-align": "center" }); $(ui.element).find("div.dpTitle").css({ "width": ui.size.width }); } } }); if(option.draggable) self._dpRoot.draggable(); //關閉按鈕事件 self._dpRoot.find("div.dpTitle > a").bind("click", function () { $.proxy(self.dpHide(), self); }); if (option.showYearAndMonth) { self._initSelYear(); self._initSelMonth(); } $(ele).focus(function () { self.dpShow(); }); $(ele).click(function () { self.dpShow(); }); //$(ele).blur(function (e) { // if ($(e.target).closest('div.dpRoot').length == 0) { // self.dpHide(); // } //}); }, _destroy: function () { var self = this, option = this.options, ele = this.element; self._dpRoot.empty(); this._prototype._destroy.call(self); }, _getColor: function (date) { var styleName = null; if (date == 3 || date == 5 || date == 12) styleName = "dpdisabled"; else if (date == 20 || date == 23 || date == 27) styleName = "dpyellow"; else styleName = "dpenable"; return styleName; }, _initSelYear: function () { var self = this, option = this.options, ele = this.element; //根據初始化設置時間計算 var today = option.initDate ? option.initDate : new Date(); this.options.initDate = today; var y = today.getFullYear(), m = today.getMonth(); //打印年 + - 10 for (var i = 0; i < 20; i++) { var varSel = (y == (y + i - 10)) ? "selected='selected'" : ""; self._dpRoot.find("select.selYear").show().append("<option value='" + (y + i - 10) + "' " + varSel + ">" + (y + i - 10) + "</option"); } //年事件 self._dpRoot.find("select.selYear").bind("change", function () { option.initDate = new Date(option.initDate.setYear($(this).val())); self._initDate(); }); }, _initSelMonth: function () { var self = this, option = this.options, ele = this.element; //根據初始化設置時間計算 var today = option.initDate ? option.initDate : new Date(); this.options.initDate = today; var y = today.getFullYear(), m = today.getMonth(); //打印月 for (var i = 0; i < 12; i++) { var varSel = (m == i) ? "selected='selected'" : ""; self._dpRoot.find("select.selMonth").show().append("<option value='" + (i + 1) + "' " + varSel + ">" + (i + 1) + "</option"); } //月事件 self._dpRoot.find("select.selMonth").bind("change", function () { var selMon = Number($(this).val()) - 1; option.initDate = new Date(option.initDate.setMonth(selMon)); self._initDate(); }); }, _initDate: function () { var self = this, option = this.options, ele = this.element; self._dpTable = self._dpRoot.find("table"); self._dpTable.empty(); if (option.language == "EN") { self._dpTable.wrapInner(_datePrinter_tmpl_EN); } //默認獲取當前日期 var today = option.initDate ? option.initDate : new Date(); this.options.initDate = today; //獲取日期中的年份 var y = today.getFullYear(), //獲取日期中的月份(需要注意的是:月份是從0開始計算,獲取的值比正常月份的值少1) m = today.getMonth(), //獲取日期中的日(方便在建立日期表格時高亮顯示當天) d = today.getDate(), //獲取當月的第一天 firstday = new Date(y, m, 1), //判斷第一天是星期幾(返回[0-6]中的一個,0代表星期天,1代表星期一,以此類推) dayOfWeek = firstday.getDay() == 0 ? 7 : firstday.getDay(), //創建月份數組 days_per_month = new Array(31, 28 + self._isLeap(y), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31), //確定日期表格所需的行數 str_nums = Math.ceil((dayOfWeek + days_per_month[m] - 1) / 7); //二維數組創建日期表格 for (i = 0; i < str_nums; i += 1) { var tr = '<tr>'; for (k = 0; k < 7; k++) { //為每個表格創建索引,從0開始 var idx = 7 * i + k; //將當月的1號與星期進行匹配 var day = idx - dayOfWeek +2; var styleName = self._getColor(day); if (option.getColor && typeof (option.getColor) == 'function') styleName = option.getColor(day); styleName += " dateTD"; (day <= 0 || day > days_per_month[m]) ? //索引小于等于0或者大于月份最大值就用空表格代替 (day = ' ', styleName = "dpBlank") : (day = idx - dayOfWeek + 2); day == d ? tr += '<td class="' + styleName + ' today">' + day + '</td>' : //高亮顯示當天 tr += '<td class="' + styleName + '">' + day + '</td>'; } tr += '</tr>'; self._dpTable.append(tr); tr = ""; } }, _isLeap: function (year) { var self = this, option = this.options, ele = this.element; return year % 4 == 0 ? (year % 100 != 0 ? 1 : (year % 400 == 0 ? 1 : 0)) : 0; }, //選中日期時設置選中值 day為currentDate當月的第幾日 _setDate: function (day) { var self = this, option = this.options, ele = this.element; self._selectDate = new Date(option.initDate.getFullYear() + '/' + (option.initDate.getMonth() + 1) + '/' + day); //設置輸入框值 $(ele).val(self.getSelectDate(), self); }, //獲取所選日期 getSelectDate: function () { var self = this, option = this.options, ele = this.element; return self._selectDate.Format(option.dateFormat); }, //顯示 dpShow: function () { var self = this, option = this.options, ele = this.element; self._dpRoot.show(); }, //隱藏 dpHide: function () { var self = this, option = this.options, ele = this.element; self._dpRoot.hide(); }, //new Guid _newGuid: function () { var guid = ""; for (var i = 1; i <= 32; i++) { var n = Math.floor(Math.random() * 16.0).toString(16); guid += n; if ((i == 8) || (i == 12) || (i == 16) || (i == 20)) { //guid += "-"; } } return guid; } });
樣式本人是業余的,勉強看看吧,由于datePrinter.js有依賴css的class名稱,貼出來datePrinter.css文件代碼如下
.dpBlank { background-color: white; cursor: not-allowed; } .dpRoot { width: 240px; position:absolute; display:none; } .today { border: 2px double #FF9900 !important; } .dpenable { background-color: #AABBFF; } .dpyellow { background-color: #FFC266; } .dpdisabled { background-color: #B0AEA4; } .dpRoot table { font-size: 13px; width: inherit; } .dpRoot table th { font-size: 12px; border: solid 2px #e8eef4; padding: 2px 3px; background-color: #e8eef4; border-collapse:initial; text-align: center; width: 22px; } .dpRoot table td { color: white; padding: 4px 5px; border: solid 2px #e8eef4; } .dpTitle { padding: 3px 0 0 0; } .dateTD { cursor: pointer; } .selYear { margin-right: 5%; display: none; font-size:14px; } .selMonth { margin-right: 5%; display: none; font-size:14px; }
以上是“js如何實現前端日歷控件”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。