search
HomeWeb Front-endJS TutorialA particularly easy-to-use lightweight date plug-in in JS

这次给大家带来JS里特别好用的轻量级日期插件,使用JS里特别好用轻量级日期插件的注意事项有哪些,下面就是实战案例,一起来看一下。

jquery的日期插件有好几款,H5中的input也可以自带日期选择。但为什么要再写一个,有两个理由,一个是引用的文件太大,而有时候只需要很简单的功能,二个是想加一些自定义的效果不好改。

我写的这个功能比较简单,可以换月,有预约效果,可以设定预约日期范围,压缩后1.4kb,先上个图,再慢慢解释:

js代码:

$.fn.datebox = function (options) {    var config = {
        $valueEle: $("#outputTime"),
        $prev: $(".datetitle #up"),
        $next: $(".datetitle #down"),
        minDate:null,
        maxDate:null,
    }
    config = $.extend(config, options);
    Date.prototype.format = function (format) {        var o = {            "M+": this.getMonth() + 1, //month
            "d+": this.getDate(), //day
            "h+": this.getHours(), //hour
            "m+": this.getMinutes(), //minute
            "s+": this.getSeconds(), //second
            "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
            "S": this.getMilliseconds() //millisecond        }        if (/(y+)/.test(format))
            format = format.replace(RegExp.$1,
                (this.getFullYear() + "").substr(4 - RegExp.$1.length));        for (var k in o)            if (new RegExp("(" + k + ")").test(format))
                format = format.replace(RegExp.$1,
                    RegExp.$1.length == 1 ? o[k] :
                        ("00" + o[k]).substr(("" + o[k]).length));        return format;
    };    var self = this;    var $ele = $(this);      
    var maxdate,mindate; 
    var nstr = new Date();  
    var ynow = nstr.getFullYear();  
    var mnow = nstr.getMonth();  
    var dnow = nstr.getDate();  
     if(!config.minDate){
           mindate=nstr;
     }else{
       mindate=new Date(config.mindate)
     } 
     if(config.maxDate){
        maxdate=new Date(config.maxDate)
     }
    self.isLeap = function (year) {        return (year % 100 == 0 ? res = (year % 400 == 0 ? 1 : 0) : res = (year % 4 == 0 ? 1 : 0));
    }
     console.log("最小日期是:",mindate.format("yyyy-MM-dd"))
     console.log("最大日期是:",maxdate.format("yyyy-MM-dd"))
     console.log("当前日期:",currentDate())
    pain();    function pain() {        var n1str = new Date(ynow, mnow, 1); //当月第一天 
        var firstday = n1str.getDay(); //当月第一天星期几
        var m_days = new Array(31, 28 + self.isLeap(ynow), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); //各月份的总天数
        var tr_str = Math.ceil((m_days[mnow] + firstday) / 7); //表格所需要行数
        //打印表格第一行(有星期标志)
        $("#datetb").remove();        var str = "
";        for (i = 0; i ";            for (k = 0; k  m_days[mnow]) ? date_str = " " : date_str = idx - firstday + 1; //过滤无效日期(小于等于零的、大于月总天数的)                 //打印日期:今天底色样式                 date_str == dnow ? str += "" : str += "";             }             str += ""; //表格的行结束        }         str += "";         str += "
周日 周一 周二 周三 周四 周五 周六
" + "

" + date_str + "

" + "

预约

" + "
" + date_str + "
" + ynow + "年" + (mnow + 1) + "月
"; //表格结束        $ele.html(str);         setDate(ynow, mnow, dnow);     }    function setDate(y, m, d) {        var current = (new Date(y, m, d, 10, 0, 0)).format("yyyy-MM-dd");         console.log(y, m, d, current);         config.$valueEle.val(current);     }    function currentDate(){        return (new Date(ynow, mnow, dnow, 10, 0, 0)).format("yyyy-MM-dd");     }     self.prev=function(){       var temp = mnow - 1;        if (temp maxdate) {                 console.log("超过最大可预约日期",nextdate.format("yyyy-MM-dd"))                return ;              }          var temp = mnow + 1;        if (temp > 11) {             mnow = 0;             ynow++;         } else {             mnow++;         }          if(ynow==maxdate.getFullYear()&&mnow==maxdate.getMonth()){                var _mday=maxdate.getDate();                if(dnow>_mday) dnow=_mday;             }         pain();       }     self.seleted=function($td){       if (!$td.hasClass('selected')) {            var day = $td.data("day");             var selectedDate=new Date(ynow, mnow, day, 1, 0, 0);            if (selectedDatemaxdate) {                  console.log("该日期不能预约");                return;             }             $(".datebox table td").removeClass('selected').children('.subscribe').remove();            $td.addClass('selected');            $td.html('

' + $td.html() + '

预约

');            dnow=day;             setDate(ynow, mnow, day);         }     }     self.getDate=function(){       return currentDate();     }     $ele.on("click", "table td", function () {       self.seleted($(this));     });     config.$prev.click(function () {      self.prev();     });    config.$next.click(function () {       self.next();     });       return self; }

css:随便玩了。

body {
    font-family: Helvetica,Microsoft JhengHei;
    font-size:1.5rem;
}*{ padding:0; margin:0;}.content {
    padding-top: 11%;
    font-family: hyxmtj,Microsoft JhengHei;
    text-shadow: 0.5px 1px 1px #e3eab7;
}.datetitle {
    width: 100%;
    background: #fed700;
    text-align: center;
    line-height: 3rem;
    -moz-border-radius: 1.7rem;
    -webkit-border-radius: 1.7rem;
    border-radius: 1.7rem;
    border-bottom: 0.25rem solid #d1a802;
    color: black;
    text-shadow: 1px 1px 1px #d1a802;
    position: relative;
}.datetitle:before {
    content: "";
    position: absolute;
    width: 62%;
    border-left: 0.5rem solid #d1a802;
    border-right: 0.5rem solid #d1a802;
    height: 1.5rem;
    bottom: -1.5rem;
    left: 0;
    margin-left: 17%;
}.datebox{ border:1px solid #d1a802;margin: 0 auto; margin-top: 1.2rem; width:68%; -moz-border-radius:1.5rem; -webkit-border-radius:1.5rem; border-radius:1.5rem; padding:0 1rem;  font-size:0.7rem; background:white; text-shadow:none;}.datebox table{width:100%; border:none;}.datebox table td{ width: 2rem;height: 2rem;text-align: center;border: 1px solid transparent;}.datebox table td p{ font-size: small; }.datebox table td.selected{border:1px solid #deaa5d; color:#deaa5d; }.datebox table td.selected .subscribe{display:block;}.datebox table td .subscribe{display:none;}.datebox table tfoot td{ font-weight: bold;}.databox #up  ,.databox #down {
    cursor: pointer;
}.datetitle #down {
    float: right;
    margin-right:2rem;
}.datetitle #up {
    float: left;
    margin-left:2rem;
}.datetitle #up:hover ,.datetitle #down:hover {
    color: green;
}

View Code

公布了isLeap,next,prev,getdate,seleted 五个方法(看名字就不需要解释了吧)。默认今天是最小的预约时间。

可以这样设定最大的可预约时间:

 var date = $(".datebox").datebox({maxDate:"2016-12-20"});

同理可以设置最小日期。

换月的时候日期会自动切换到可预约的日期。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

微信分享功能的开发

公众号支付接口的开发

webpack自动刷新与解析的使用

The above is the detailed content of A particularly easy-to-use lightweight date plug-in in 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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor