css+html implements simple calendar
This article mainly introduces in detail a simple calendar implemented by a combination of html, css, and javascript. It has a certain reference value. Interested friends can refer to many places on the
web page. Calendar display, selection, etc. are all used. This article uses html, css, and javascript to implement a simple calendar. After completion, the effect will be similar to the effect on the left side of the page. You can switch between the previous month and the next month. It can also be expanded according to the actual situation.
html
The html part is relatively simple, declare a p, and the specific html is generated with javascript. The overall content is roughly like this:
<!doctype html> <html> <head> <meta charset='utf-8'> <link rel='stylesheet' href='外部的css文件路径' /> <title>demo</title> </head> <body> <p class='calendar' id='calendar'></p> <script type='text/javascript' src='外部的javascript文件路径'></script> </body> </html>
css
/* 整体设置 */ *{margin:0px;padding:0px;} /** * 设置日历的大小 */ .calendar{ width: 240px; height: 400px; display: block; } /** * 设置日历顶部盒子 */ .calendar .calendar-title-box{ position: relative; width: 100%; height: 36px; line-height: 36px; text-align:center; border-bottom: 1px solid #ddd; } /** * 设置上个月的按钮图标 */ .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; } /** * 设置下个月的按钮图标 */ .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; } /* 设置日历表格样式 */ .calendar-table{ width: 100%; border-collapse: collapse; text-align:center; } /* 表格行高 */ .calendar-table tr{ height: 30px; line-height: 30px; } /* 当前天 颜色特殊显示 */ .currentDay { color: red; } /* 本月 文字颜色 */ .currentMonth { color: #999; } /* 其他月颜色 */ .otherMonth{ color: #ede; }
There is basically nothing to say about style settings, some simple settings. For example, the special icons representing "last month" and "next month" are absolutely positioned and styled using the border attribute in CSS.
javascript Date object
Before starting the formal js code, you need to understand the Date object in js. Through the Date object, you can get the year, month, day, hour, minute, second, and timestamp. Information,
var d1 = new Date(); // 获取当前系统时间 我现在的时间是 2016年4月25日 星期一 d1.getFullYear(); // 获取年信息, 2016 d1.getMonth(); // 获取月信息(从0开始 范围:0-11) 3 d1.getDate(); // 获取天信息 此处结果:25 d1.getDay(); // 获取星期信息 (0-6) 此处结果: 1
You can also directly set the year, month and day information during initialization
# 设置 2016年3月15日 var d2 = new Date(2016, 2, 15); // 月是从0开始计数, 需要减一 d2.getFullYear(); // 2016 d2.getMonth(); // 2 d2.getDate(); // 15 d2.toLocaleDateString(); // "2016/3/15" 证明设置正确
The calendar will involve issues such as how many days in each month, which is very simple in js. If When setting the year, month and day, if it exceeds the current month, js will automatically calculate it as the next month. For example, April only has 30 days. If it is set to the 31st, the obtained Date type will automatically be calculated as May 1st; if it is set to On May 0, js will process it as April 30, so May-1 is April 29
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
Understand the Date object in js Basic usage, next is the code implementation part, the overall idea is this: 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 from dateObj, and the date in the table is obtained from dateObj. All the information of the 1st corresponding to the year and month can be determined, and the position of the 1st in the first row of the table can be determined, and the last month can be calculated backwards. Data for several days, data for this month and next month are being pushed.
Specific steps:
1. Declare the dateObj variable and assign the initial value to the current system time
2. Render the html element in calendar p
3. Get the information on the 1st of the month through dateObj, and Use this to traverse all the dates in the table
4. Bind events to the previous month and next month icon
(function(){ /* * 用于记录日期,显示的时候,根据dateObj中的日期的年月显示 */ var dateObj = (function(){ var _date = new Date(); // 默认为当前系统时间 return { getDate : function(){ return _date; }, setDate : function(date) { _date = date; } }; })(); // 设置calendar p中的html部分 renderHtml(); // 表格中显示日期 showCalendarData(); // 绑定事件 bindEvent(); /** * 渲染html结构 */ function renderHtml() { var calendar = document.getElementById("calendar"); var titleBox = document.createElement("p"); // 标题盒子 设置上一月 下一月 标题 var bodyBox = document.createElement("p"); // 表格区 显示数据 // 设置标题盒子中的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); // 添加到calendar p中 // 设置表格区的html结构 bodyBox.className = 'calendar-body-box'; var _headHtml = "<tr>" + "<th>日</th>" + "<th>一</th>" + "<th>二</th>" + "<th>三</th>" + "<th>四</th>" + "<th>五</th>" + "<th>六</th>" + "</tr>"; var _bodyHtml = ""; // 一个月最多31天,所以一个月最多占6行表格 for(var i = 0; i < 6; i++) { _bodyHtml += "<tr>" + "<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>"; // 添加到calendar p中 calendar.appendChild(bodyBox); } /** * 表格中显示数据,并设置类名 */ function showCalendarData() { var _year = dateObj.getDate().getFullYear(); var _month = dateObj.getDate().getMonth() + 1; var _dateStr = getDateStr(dateObj.getDate()); // 设置顶部标题栏中的 年、月信息 var calendarTitle = document.getElementById("calendarTitle"); var titleStr = _dateStr.substr(0, 4) + "年" + _dateStr.substr(4,2) + "月"; calendarTitle.innerText = titleStr; // 设置表格中的日期数据 var _table = document.getElementById("calendarTable"); var _tds = _table.getElementsByTagName("td"); var _firstDay = new Date(_year, _month - 1, 1); // 当前月第一天 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())) { // 当前天 _tds[i].className = 'currentDay'; }else if(_thisDayStr.substr(0, 6) == getDateStr(_firstDay).substr(0, 6)) { _tds[i].className = 'currentMonth'; // 当前月 }else { // 其他月 _tds[i].className = 'otherMonth'; } } } /** * 绑定上个月下个月事件 */ function bindEvent() { var prevMonth = document.getElementById("prevMonth"); var nextMonth = document.getElementById("nextMonth"); addEvent(prevMonth, 'click', toPrevMonth); addEvent(nextMonth, 'click', toNextMonth); } /** * 绑定事件 */ 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); } } } /** * 点击上个月图标触发 */ function toPrevMonth() { var date = dateObj.getDate(); dateObj.setDate(new Date(date.getFullYear(), date.getMonth() - 1, 1)); showCalendarData(); } /** * 点击下个月图标触发 */ function toNextMonth() { var date = dateObj.getDate(); dateObj.setDate(new Date(date.getFullYear(), date.getMonth() + 1, 1)); showCalendarData(); } /** * 日期转化为字符串, 4位年+2位月+2位日 */ function getDateStr(date) { var _year = date.getFullYear(); var _month = date.getMonth() + 1; // 月从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 the date in the table is clicked is not added. You can use the bindEvent function Add the following code to obtain the information of 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')); }); }
Related recommendations:
javascript html5 canvas implements a draggable province map of China
The above is the detailed content of css+html implements simple calendar. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

An important tool for organizing your daily work and routine in Windows 11 is the display of time and date in the taskbar. This feature is usually located in the lower right corner of the screen and gives you instant access to the time and date. By clicking this area, you can bring up your calendar, making it easier to check upcoming appointments and dates without having to open a separate app. However, if you use multiple monitors, you may run into issues with this feature. Specifically, while the clock and date appear on the taskbar on all connected monitors, the ability to click the date and time on a second monitor to display the calendar is unavailable. As of now, this feature only works on the main display - it's unlike Windows 10, where clicking on any

Many users want to use the win10 calendar tool to check the current number of days, but the calendar does not automatically display this function. In fact, we only need to make simple settings to see the cumulative number of weeks this year ~ win10 calendar displays weeks Digital setting tutorial: 1. Enter calendar in the search in the lower left corner of the desktop and open the application. 2. In the open calendar application, click the "gear" icon in the lower left corner, and the settings will pop up on the right. We click "Calendar Settings" 3. Continue in the open calendar settings, find "Week Number" and then change the week Just adjust the number option to "the first day of the year". 4. After completing the above settings, click "Week" to see this year's week number statistics.

If your Outlook calendar cannot sync with Google Calendar, Teams, iPhone, Android, Zoom, Office account, etc., please follow the steps below to resolve the issue. The calendar app can be connected to other calendar services such as Google Calendar, iPhone, Android, Microsoft Office 365, etc. This is very useful because it can sync automatically. But what if OutlookCalendar fails to sync with third-party calendars? Possible reasons could be selecting the wrong calendar for synchronization, calendar not visible, background application interference, outdated Outlook application or calendar application, etc. Preliminary fix for Outlook calendar not syncing

Some friends who use the win0 system have encountered the situation where the win10 calendar cannot be opened. This is just a normal computer glitch. It can be solved in the privacy settings of the win10 system. Today, the editor has brought a detailed solution. Below Let’s take a look. Solution to the problem that the calendar cannot be opened in the lower right corner of win10 1. Click Start in the win10 system → click the program list button above → find Pinyin (Chinese) R → Calendar 2. When using it for the first time, new events may not be opened (mouse If you lean up, there will be no dark blue selected), you can set it in privacy. Click the three-bar icon in the upper left corner of the desktop → there will be a settings menu at the bottom; 3. Click Privacy in the pop-up interface; 4. If you have used settings before, you can click on the left

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

The calendar can help users record your schedule and even set reminders. However, many users are asking what to do if calendar event reminders do not pop up in Windows 10? Users can first check the Windows update status or clear the Windows App Store cache to perform the operation. Let this site carefully introduce to users the analysis of the problem of Win10 calendar event reminder not popping up. To add calendar events, click the "Calendar" program in the system menu. Click the left mouse button on a date in the calendar. Enter the event name and reminder time in the editing window, and click the "Save" button to add the event. Solving the problem of win10 calendar event reminder not popping up

The Lost Purchasing Office is confirmed to be updated at 11 am on February 28th. Players can go to Taobao to search the Purchasing Office and select the store category to purchase. This time we bring you the MBCC birthday party series and 2024 Desk Calendar peripherals. Come together. Take a look at the product details this time. No Period Lost Purchasing Office: New calendar and birthday series peripherals! There is something new in the Lost Procurement Office! - Pre-sale time: February 28, 2024 11:00 - March 13, 2024 23:59 Purchase address: Taobao search [Unexpected Lost Purchasing Office] Select [Store] category to enter the store for purchase; peripheral introduction: The new peripherals released this time are MBCC birthday party series and 2024 desk calendar peripherals. Please click on the long image for details. The Purchasing Office introduces new peripherals—MBCC students

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price
