search
HomeWeb Front-endJS TutorialIdeas and code for implementing calendar in native js

本篇文章给大家带来的内容是关于原生js实现日历的思路与代码,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

demo效果:

Ideas and code for implementing calendar in native js

实现日历的思路:

1、利用new Date()获取今天日期

2、判断今年是平年还是闰年,确定今年每个月有多少天

3、确定今天日期所在月的第一天是星期几

4、计算出日历的行数

5、利用今天日期所在月的天数与该月第一天星期几来渲染日历表格

6、左右切换月份

源码:

html

<div class="calendar-container">
    <div class="calendar-header">
        <div class="left btn"><</div>
        <div class="year"></div>
        <div class="right btn">></div>
    </div>
    <div class="calendar-body">
        <div class="week-row">
            <div class="week box">日</div>
            <div class="week box">一</div>
            <div class="week box">二</div>
            <div class="week box">三</div>
            <div class="week box">四</div>
            <div class="week box">五</div>
            <div class="week box">六</div>
        </div>
        <div class="day-rows">
            <!--日期的渲染的地方-->
        </div> 
    </div>
</div>

css

.calendar-container{
    width: calc(31px*7 + 1px);
    }
.calendar-header{
    display: flex;    
    justify-content: space-between;
    }
.year{
    text-align: center;    
    line-height: 30px;
    }
.btn{
    width: 30px;    
    height: 30px;    
    text-align: center;    
    line-height: 30px;    
    cursor: pointer;
    }
.calendar-body{
    border-right: 1px solid #9e9e9e;    
    border-bottom: 1px solid #9e9e9e;
    }
.week-row, 
.day-rows, 
.day-row{
    overflow: hidden;
    }
.box{
    float: left;    
    width: 30px;    
    height: 30px;    
    border-top: 1px solid #9e9e9e;    
    border-left: 1px solid #9e9e9e;    
    text-align: center;    
    line-height: 30px;
    }
.week{
    background: #00bcd4;
    }
.day{
    background: #ffeb3b;
    }
.curday{ 
   background: #ff5722;
   }

js

// 获取今天日期
let curTime = new Date(),
    curYear = curTime.getFullYear(),
    curMonth = curTime.getMonth(),
    curDate = curTime.getDate();
    console.log(curTime, curYear, curMonth, curDate)
    // 判断平年还是闰年
    function isLeapYear(year){    
    return (year%400 === 0) || ((year%4 === 0) && (year%100 !== 0))
}
function render(curYear, curMonth){    
document.querySelector(&#39;.year&#39;).innerHTML = `${curYear}年${curMonth + 1}月`;    
// 判断今年是平年还是闰年,并确定今年的每个月有多少天    
let daysInMonth = [31, isLeapYear(curYear) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];    
// 确定今天日期所在月的第一天是星期几    
let firstDayInMonth = new Date(curYear, curMonth, 1),
        firstDayWeek = firstDayInMonth.getDay();    
        // 根据当前月的天数和当前月第一天星期几来确定当前月的行数    
        let calendarRows = Math.ceil((firstDayWeek + daysInMonth[curMonth])/7);    
        // 将每一行的日期放入到rows数组中    
        let rows = [];    
        // 外循环渲染日历的每一行    
        for(let i = 0; i < calendarRows; i++){
        rows[i] = `<p class="day-row">`;        
        // 内循环渲染日历的每一天        
        for(let j = 0; j < 7; j++){            
        // 内外循环构成了一个calendarRows*7的表格,为当前月的每个表格设置idx索引;            
        // 利用idx索引与当前月第一天星期几来确定当前月的日期            
        let idx = i*7 + j,
                date = idx - firstDayWeek + 1;            
                // 过滤掉无效日期、渲染有效日期            
                if(date <= 0 || date > daysInMonth[curMonth]){
                rows[i] += `<p class="day box"></p>`
            }else if(date === curDate){
                rows[i] += `<p class="day box curday">${date}</p>`
            }else{
                rows[i] += `<p class="day box">${date}</p>`
            }
        }
        rows[i] += `</p>`
    }    let dateStr = rows.join(&#39;&#39;);    
    document.querySelector(&#39;.day-rows&#39;).innerHTML = dateStr;
}
// 首次调用render函数
render(curYear, curMonth);
let leftBtn = document.querySelector(&#39;.left&#39;),
    rightBtn = document.querySelector(&#39;.right&#39;);
    // 向左切换月份
leftBtn.addEventListener(&#39;click&#39;, function(){
    curMonth--;    
    if(curMonth < 0){
        curYear -= 1;
        curMonth = 11;
    }
    render(curYear, curMonth);
})
// 向右切换月份
rightBtn.addEventListener(&#39;click&#39;, function(){
    curMonth++;    
    if(curMonth > 11){
        curYear += 1;
        curMonth = 0;
    }
    render(curYear, curMonth);
})

小结:

1、为了实现左右切换月份,将日历日期渲染代码放入到了render函数,方便月份切换后重新渲染;

2、确定当前月的行数时,要结合当前月的天数与当前月第一天星期几来共同确定;

3、原生js日历中比较核心的就是如何确定每一天的日期,在这儿利用了内外循环,内外循环构成了一个calendarRows*7的表格,为当前月的每个表格设置idx索引;利用idx索引与当前月第一天星期几来确定当前月的日期;记得要过滤掉无效日期!!!

相关推荐:

JS日历 推荐_时间日期

推荐一个小巧的JS日历_时间日期

The above is the detailed content of Ideas and code for implementing calendar in native js. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor