Home Web Front-end JS Tutorial JS implements a simple calendar

JS implements a simple calendar

Mar 30, 2017 pm 03:56 PM

It is mainly divided into three parts, 1: Obtaining the li element 2: How to fill in the corresponding date 3: How to obtain the event of clicking the li element.

1: Obtain the li element through the children attribute of the relationship between nodes (two for loop traversals);

2: When traversing to fill in the date, in the first The row determines what day of the week the first day of the month falls on, and then starts filling in from the first day, until it is greater than the number of days in the current month, it stops filling in, and starts filling in the date of the next month. The first row displays the date of last month: the number of days in the previous month displays the starting value = calculates the number of days in the last month - the value of the day of the week on the first day of this month - 1, and then displays the starting value of the number of days in the previous month in the first row Add by yourself.

3: Use JS event bubbling to obtain the innerHTML of li and display the corresponding date

Rendering:

JS implements a simple calendar

The code is as follows:


<!doctype html>
<html lang="en">
 <head>
 <meta charset="UTF-8">
 <meta name="Generator" content="EditPlus®">
 <meta name="Author" content="">
 <meta name="Keywords" content="">
 <meta name="Description" content="">
 <title>calendar</title>
 <style>
 .clear:after{
 content:"";
 display:table;
 clear:both;
 }
 .left{
 float:left;
 }
 ul{
 padding:0px;
 margin-top:5px;
 margin-bottom:0px;
 }
 ul>li{
 float:left;
 list-style:none;
 width:30px;
 height: 21px;
 border: 1px solid #ccc;
 text-align:center;
 }
 .gray{
 color:#766565;
 }
 .top {
 height:25px;
 }
 .top .lf-tri{
 border:10px solid transparent;
 border-right-color:black;
 margin-top:4px;
 }
 .top .rf-tri{
 border:10px solid transparent;
 border-left-color:black;
 margin-top:4px;
 }
 .top .content{
 width:185px;
 height:5px;
 text-align:center;
 }
 </style>
 </head>
 <body> 
 <p class="top clear">
 <p class="left lf-tri" onclick="lastMonth()"></p>
 <p class="left content">2017年2月1日</p>
 <p class="left rf-tri" onclick=" nextMonth()"></p>
 </p>
 <p>
 <p id="week">
 <ul class="clear">
 <li>日</li>
 <li>一</li>
 <li>二</li>
 <li>三</li>
 <li>四</li>
 <li>五</li>
 <li>六</li>
 <ul>
 </p>
 <p id="date" onclick=&#39;getDateNum(event)&#39;>
 <ul class="clear">
 <li>30</li>
 <li>31</li>
 <li>1</li>
 <li>2</li>
 <li>3</li>
 <li>4</li>
 <li>5</li>
 </ul>
 <ul class="clear">
 <li>6</li>
 <li>7</li>
 <li>8</li>
 <li>9</li>
 <li>10</li>
 <li>11</li>
 <li>12</li>
 </ul>
 <ul class="clear">
 <li>13</li>
 <li>14</li>
 <li>15</li>
 <li>16</li>
 <li>17</li>
 <li>18</li>
 <li>19</li>
 </ul>
 <ul class="clear">
 <li>20</li>
 <li>21</li>
 <li>22</li>
 <li>23</li>
 <li>24</li>
 <li>25</li>
 <li>26</li>
 </ul>
 <ul class="clear">
 <li>27</li>
 <li>28</li>
 <li>1</li>
 <li>2</li>
 <li>3</li>
 <li>4</li>
 <li>5</li>
 </ul>
 <ul class="clear">
 <li>27</li>
 <li>28</li>
 <li>1</li>
 <li>2</li>
 <li>3</li>
 <li>4</li>
 <li>5</li>
 </ul>
 </p>
 <p>
 <script>
 function $(id){
 return document.getElementById(id);
 }
 function change(cls){
 return document.getElementsByClassName(cls);
 }
 function getDateNum(e) {
 console.log(e && e.target.nodeName)//打印发生事件的元素,再获取元素nodeName
 if(e.target.nodeName=="LI"){//先判断nodeName是LI
 if(e.target.className!="gray"){//点击本月的日期,显示在日期栏
 change("content")[0].innerHTML = year+&#39;年&#39;+(month+1)+&#39;月&#39;+e.target.innerHTML+&#39;日&#39;;
 }else{//点击灰色日期即(上个月或者下个月日期)切换到当月
 if(e.target.innerHTML>14){
 lastMonth();
 }else {
 nextMonth();
 }
 }
 }
 }
 //获取年、月
 var today = new Date();
 var year=today.getFullYear(), month = today.getMonth();
 var totalDay;
 var uls=$("date").children,list;
 function loadCalendar(){
 totalDay=getMonthDays(year,month+1);//计算一个月的天数
 var firstDay = (new Date(year,month,1)).getDay();//计算每个月1号在星期几
 var lastMonthDay=getMonthDays(year,month);
 var lastDayCal=lastMonthDay-firstDay+1;//计算上个月在第一行显示的天数
 //获取ul元素
 var num=1 ,nextNum=1;//日期显示
 // 类数组对象 转 数组
 //uls = Array.prototype.slice.call(uls)
 //获取li元素 填充
 for(var r=0;r<uls.length;r++){
 list=uls[r].children;//遍历ul,获得li
 for(var line=0;line<list.length;line++){
 if(r==0){//在第一行 与第一天进行判断 大于等于第一天时载入日期
 if(line>=firstDay){
 list[line].innerHTML=num++;
 list[line].setAttribute("class","");
 }else {
 list[line].innerHTML=lastDayCal++;//第一行的上个月天数显示
 list[line].setAttribute("class","gray");
 }
 }else {
 //判断是否超出天数 ,不超出则继续加,超出则显示下个月日期
 if(num<=totalDay){
 list[line].setAttribute("class","");
 list[line].innerHTML=num++;
 }else {
 list[line].innerHTML=nextNum++;//下个月日期显示
 list[line].setAttribute("class","gray");
 }
 }
 }
 }
 }
 loadCalendar();
 function getMonthDays(year,month){
 //判断2月份天数
 if(month==2){
 days= (year%4==0)&&(year%100!=0)||(year%400==0)? 29:28;
 }else {
 //1-7月 单数月为31日 
 if(month<7){
 days= month%2==1?31:30;
 }else {
 //8-12月 双月为31日
 days = month%2==0?31:30;
 }
 }
 return days; 
 }
 //右击箭头下个月
 //change("rf-tri")[0].onclick =
 function nextMonth() {
 month++;
 if(month>11){
 year+=1;
 month=0;
 }
 change("content")[0].innerHTML=year+"年"+(month+1)+"月"+"1日";
 //console.log(month+1);
 loadCalendar();
 }
 //左击箭头上个月
 //change("lf-tri")[0].onclick =
 function lastMonth() {
 month--;
 if(month<0){
 month=11;
 year-=1;
 }
 change("content")[0].innerHTML=year+"年"+(month+1)+"月"+"1日";
 //console.log(month+1);
 loadCalendar();
 }
 </script>
 </body>
</html>
Copy after login

For more articles related to JS implementing a simple calendar, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles