Calendar display, selection, etc. are used in many places on the web page. This article uses html, css, and javascript to implement a simple calendar. After completion, the effect is similar to the effect on the left side of the page. You can switch to the previous month or next month. It can also be expanded according to actual conditions.
html
The html part is relatively simple, declare a div, and the specific html is generated using javascript. The overall content is roughly like this:
<!doctype html><html><head> <meta charset='utf-8'> <link rel='stylesheet' href='External css file path' /> <title>demo</title></head><body> <div class='calendar' id='calendar'></div> <script type='text/javascript' src='External javascript file path'></script></body></html>
css
/* Overall settings*/*{margin:0px;padding:0px;}/** * Set the size of the calendar*/.calendar{ width: 240px; height: 400px; display: block;}/** * Set the top box of the calendar*/.calendar .calendar-title-box{ position: relative; width: 100%; height: 36px; line-height: 36px; text-align:center; border-bottom: 1px solid #ddd;}/** * Set the button icon for last month*/.calendar .prev-month { position: absolute; top: 12px; left: 0px; display: inline-block; width: 0px; height: 0px; border-left: 0px; border-top: 6px solid transparent; border-right: 8px solid #999; border-bottom: 6px solid transparent; cursor: pointer;}/** * Set next month's button icon*/.calendar .next-month { position: absolute; top: 12px; right: 0px; display: inline-block; width: 0px; height: 0px; border-right: 0px; border-top: 6px solid transparent; border-left: 8px solid #999; border-bottom: 6px solid transparent; cursor: pointer;}/* Set calendar table style*/.calendar-table{ width: 100%; border-collapse: collapse; text-align:center;}/* Table line height*/.calendar-table tr{ height: 30px; line-height: 30px;}/* Current day color special display*/.currentDay { color: red;}/* This month's text color*/.currentMonth { color: #999;}/* Other month colors*/.otherMonth{ color: #ede;}There is basically nothing to say about style settings, some simple settings. For example, the special one is the icon that represents "Last month" and "Next month", which adopts absolute positioning and uses the border attribute in CSS to set styles.
javascript Date object
Before starting the formal js code, you need to understand the Date object in js. Through the Date object, you can obtain information such as year, month, day, time, and time stamps. For specific reference: http://www.w3school.com.cn/jsref/jsref_obj_date.asp
var d1 = new Date(); // Get the current system time My current time is Monday, April 25, 2016 d1.getFullYear(); // Get the annual information, 2016 d1.getMonth(); // Get the monthly information (starting from 0: 0-11) 3 d1.getDate(); // Get the day information Here the result: 25 d1.getDay(); // Get the weekly information (0-6) Here the result: 1
You can also set the year, month and date information directly during initialization
# Set March 15, 2016 var d2 = new Date(2016, 2, 15); // Months are counted from 0, and you need to subtract one d2.getFullYear(); // 2016 d2.getMonth(); // 2 d2.getDate(); // 15 d2.toLocaleDateString(); // "2016/3/15" proves that the settings are correct
The calendar involves issues such as how many days per month. It is very simple in js. If the year, month and day are set, if it exceeds the current month, js will automatically calculate the next month. For example, April has only 30 days. If it is set to 31, the obtained Date type will automatically calculate the May 1st. If it is set to 0, js will process it as April 30, then May-1 is April 29th.
var d3 = new Date(2016, 3, 30);d3.toLocaleDateString(); // "2016/4/30"var d4 = new Date(2016, 3, 31);d4.toLocaleDateString(); // "2016/5/1"var d5 = new Date(2016, 3, 33);d5.toLocaleDateString(); // "2016/5/3"var d6 = new Date(2016, 4, 1);d6.toLocaleDateString(); // "2016/5/1"var d7 = new Date(2016, 4, 0);d7.toLocaleDateString(); // "2016/4/30"var d8 = new Date(2016, 4, -3);d8.toLocaleDateString(); // "2016/4/27"
javascript
After understanding the basic usage of Date objects in js, the next step is the code implementation part. The overall idea is as follows: define a global dateObj variable to record the year and month information that needs to be displayed in the table. The content in the title is taken based on dateObj. The date in the table takes all the information of No. 1 corresponding to year and month in dateObj, and then determines the position of No. 1 in the first row of the table, so as to reverse the data of the last few days of the previous month, and the data of this month and next month are being pushed back.
Specific steps:
1. Declare the dateObj variable and assign the initial value to the current system time
2. Render html elements in calendar div
3. Get the information on the 1st of the month through dateObj and use it to traverse all dates in the table.
4. Bind events for the previous month and next month icons
(function(){ /* * Used to record dates. When displayed, it will be displayed according to the year and month of the date in dateObj*/ var dateObj = (function(){ var _date = new Date(); // Default is the current system time return { getDate : function(){ return _date; }, setDate : function(date) { _date = date; } }; })(); // Set the html part in the calendar div renderHtml(); // Show dates in the table showCalendarData(); // Binding event bindEvent(); /** * Rendering html structure*/ function renderHtml() { var calendar = document.getElementById("calendar"); var titleBox = document.createElement("div"); // Title box sets the title of the previous month next month var bodyBox = document.createElement("div"); // Table area displays data// Set html titleBox.className = 'calendar-title-box'; titleBox.innerHTML = "<span class='prev-month' id='prevMonth'></span>" + "<span class='calendar-title' id='calendarTitle'></span>" + "<span id='nextMonth' class='next-month'></span>"; calendar.appendChild(titleBox); // Add to calendar div// Set the html structure of the table area bodyBox.className = 'calendar-body-box'; var _headHtml = "<tr>" + "<th>day</th>" + "<th>one</th>" + "<th>two</th>" + "<th>three</th>" + "<th>four</th>" + "<th>five</th>" + "<th>six</th>" + "</tr>"; var _bodyHtml = ""; // A maximum of 31 days a month, so a maximum of 6 rows of tables are occupied in a month for(var i = 0; i < 6; i++) { _bodyHtml += "<tr>" + "<td></td>" + "<td></td>" + "<td></td>" + "<td></td>" + "<td></td>" + "<td></td>" + "<td></td>" + "<td></td>" + "<td></td>" + "</tr>"; } bodyBox.innerHTML = "<table id='calendarTable' class='calendar-table'>" + _headHtml + _bodyHtml + "</table>"; // Add to calendar div calendar.appendChild(bodyBox); } /** * Show data in the table and set the class name*/ function showCalendarData() { var _year = dateObj.getDate().getFullYear(); var _month = dateObj.getDate().getMonth() + 1; var _dateStr = getDateStr(dateObj.getDate()); // Set year and month information in the top title bar var calendarTitle = document.getElementById("calendarTitle"); var titleStr = _dateStr.substr(0, 4) + "year" + _dateStr.substr(4,2) + "month"; calendarTitle.innerText = titleStr; // Set date data in the table var _table = document.getElementById("calendarTable"); var _tds = _table.getElementsByTagName("td"); var _firstDay = new Date(_year, _month - 1, 1); // The first day of the current month for(var i = 0; i < _tds.length; i++) { var _thisDay = new Date(_year, _month - 1, i + 1 - _firstDay.getDay()); var _thisDayStr = getDateStr(_thisDay); _tds[i].innerText = _thisDay.getDate(); //_tds[i].data = _thisDayStr; _tds[i].setAttribute('data', _thisDayStr); if(_thisDayStr == getDateStr(new Date())) { // Current day_tds[i].className = 'currentDay'; }else if(_thisDayStr.substr(0, 6) == getDateStr(_firstDay).substr(0, 6)) { _tds[i].className = 'currentMonth'; // Current month}else { // Other months_tds[i].className = 'otherMonth'; } } } /** * Bind the event of the previous month next month*/ function bindEvent() { var prevMonth = document.getElementById("prevMonth"); var nextMonth = document.getElementById("nextMonth"); addEvent(prevMonth, 'click', toPrevMonth); addEvent(nextMonth, 'click', toNextMonth); } /** * Binding event*/ function addEvent(dom, eType, func) { if(dom.addEventListener) { // DOM 2.0 dom.addEventListener(eType, function(e){ func(e); }); } else if(dom.attachEvent){ // IE5+ dom.attachEvent('on' + eType, function(e){ func(e); }); } else { // DOM 0 dom['on' + eType] = function(e) { func(e); } } } /** * Click the icon of the last month to trigger */ function toPrevMonth() { var date = dateObj.getDate(); dateObj.setDate(new Date(date.getFullYear(), date.getMonth() - 1, 1)); showCalendarData(); } /** * Click the icon of the next month to trigger */ function toNextMonth() { var date = dateObj.getDate(); dateObj.setDate(new Date(date.getFullYear(), date.getMonth() + 1, 1)); showCalendarData(); } /** * Date is converted into a string, 4-bit year + 2-bit month + 2-bit day*/ function getDateStr(date) { var _year = date.getFullYear(); var _month = date.getMonth() + 1; // Month counts from 0 var _d = date.getDate(); _month = (_month > 9) ? ("" + _month) : ("0" + _month); _d = (_d > 9) ? ("" + _d) : ("0" + _d); return _year + _month + _d; }})();In this example, the event when clicking the date in the table is not added. You can add the following code to the bindEvent function to obtain the information about the clicked date.
var table = document.getElementById("calendarTable");var tds = table.getElementsByTagName('td');for(var i = 0; i < tds.length; i++) { addEvent(tds[i], 'click', function(e){ console.log(e.target.getAttribute('data')); });}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.