Home Web Front-end JS Tutorial A particularly easy-to-use lightweight date plug-in in JS

A particularly easy-to-use lightweight date plug-in in JS

Mar 16, 2018 pm 02:27 PM
javascript use lightweight

这次给大家带来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 = "<table id=&#39;datetb&#39; cellspacing=&#39;0&#39;><tr><td>周日</td><td>周一</td><td>周二</td><td>周三</td><td>周四</td><td>周五</td><td>周六</td></tr>";        for (i = 0; i < tr_str; i++) { //表格的行
            str += "<tr>";            for (k = 0; k < 7; k++) { //表格每行的单元格
                idx = i * 7 + k; //单元格自然序列号
                date_str = idx - firstday + 1; //计算日期
                (date_str <= 0 || date_str > m_days[mnow]) ? date_str = " " : date_str = idx - firstday + 1; //过滤无效日期(小于等于零的、大于月总天数的)
                //打印日期:今天底色样式
                date_str == dnow ? str += "<td class=&#39;selected&#39; data-day=" + date_str + ">" + "<p>" + date_str + "</p>" + "<p class=&#39;subscribe&#39;>预约</p>" + "</td>" : str += "<td  data-day=" + date_str + ">" + date_str + "</td>";
            }
            str += "</tr>"; //表格的行结束        }
        str += "<tfoot><tr><td colspan=&#39;7&#39;>" + ynow + "年" + (mnow + 1) + "月</td></tr></tfoot>";
        str += "</table>"; //表格结束        $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 < 0) {
            mnow = 11;
            ynow--;
        } else {             var prevdate=new Date(ynow, mnow-1, 31, 10, 0, 0);            if (prevdate <mindate) {
                console.log("超过最小可预约日期",prevdate.format("yyyy-MM-dd"))                return;
            }
            mnow--;
        }         if(ynow==mindate.getFullYear()&&mnow==mindate.getMonth()){                 var _mday=mindate.getDate();                if(dnow<_mday) dnow=_mday;
            }
        pain(); 
    }
    self.next=function(){           var nextdate=new Date(ynow, mnow+1, 1, 10, 0, 0);            if (nextdate>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 (selectedDate<mindate||selectedDate>maxdate) {
                 console.log("该日期不能预约");                return;
            }
            $(".datebox table td").removeClass('selected').children('.subscribe').remove();
           $td.addClass('selected');
           $td.html('<p>' + $td.html() + '</p><p class="subscribe">预约</p>');
           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;
}
Copy after login

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;
}
Copy after login

View Code

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

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

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

同理可以设置最小日期。

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

相信看了本文案例你已经掌握了方法,更多精彩请关注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 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
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Best lightweight Linux distributions for low-end or older computers Best lightweight Linux distributions for low-end or older computers Mar 06, 2024 am 09:49 AM

Looking for the perfect Linux distribution to breathe new life into your old or low-end computer? If yes, then you have come to the right place. In this article, we'll explore some of our top picks for lightweight Linux distributions that are specifically tailored for older or less powerful hardware. Whether the motivation behind this is to revive an aging device or simply maximize performance on a budget, these lightweight options are sure to fit the bill. Why choose a lightweight Linux distribution? There are several advantages to choosing a lightweight Linux distribution, the first of which is getting the best performance on the least system resources, which makes them ideal for older hardware with limited processing power, RAM, and storage space. Beyond that, with heavier resource intensive

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Which computer should Geographic Information Science majors choose? Which computer should Geographic Information Science majors choose? Jan 13, 2024 am 08:00 AM

Recommended computers suitable for students majoring in geographic information science 1. Recommendation 2. Students majoring in geographic information science need to process large amounts of geographic data and conduct complex geographic information analysis, so they need a computer with strong performance. A computer with high configuration can provide faster processing speed and larger storage space, and can better meet professional needs. 3. It is recommended to choose a computer equipped with a high-performance processor and large-capacity memory, which can improve the efficiency of data processing and analysis. In addition, choosing a computer with larger storage space and a high-resolution display can better display geographic data and results. In addition, considering that students majoring in geographic information science may need to develop and program geographic information system (GIS) software, choose a computer with better graphics processing support.

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Analyze why Golang is suitable for high concurrency processing? Analyze why Golang is suitable for high concurrency processing? Feb 29, 2024 pm 01:12 PM

Golang (Go language) is a programming language developed by Google, aiming to provide an efficient, concise, concurrent and lightweight programming experience. It has built-in concurrency features and provides developers with powerful tools to perform well in high-concurrency situations. This article will delve into the reasons why Golang is suitable for high-concurrency processing and provide specific code examples to illustrate. Golang concurrency model Golang adopts a concurrency model based on goroutine and channel. goro

See all articles