Home > Web Front-end > JS Tutorial > body text

A simple horizontal javascript date control_time and date

WBOY
Release: 2016-05-16 19:07:04
Original
1814 people have browsed it

The specific requirements are:
1. The date table fills up the page horizontally.
2. The date list of each month is displayed in a row horizontally, instead of displaying a box like many date controls on the Internet.
3. It is required that only year, month and day are optional. After selecting year or month, the corresponding date will be automatically updated (this is available in every date control).
4. The current year and month are displayed by default, the current date is highlighted, and the current week (week of the year) and day of the week are displayed.
5. After selecting a date, the current date will be highlighted, and the week and week display will be automatically updated.
6. Provide an interface to set the display style of a specific date.
6. Others are some interface display issues.

I thought it was just a date control. It’s relatively simple to make, but it’s especially horizontal. This is the first time I’ve heard of this need!
This is my first time writing something like a calendar. However, the trouble this time still lies in the calculation of weeks and the implementation of the interface for setting specific dates provided in the end. But after some analysis, it was solved very well. .
Main summary:
1. Use closures to hide internal functions and variables to prevent variable pollution. Finally, only one external interface is provided: setDateStyle
2. Calculating the number of days in February each year is not by judging leap years, but by judging whether February 29 exists. If it does not exist, it is 28 days.
3. To calculate the week, you must first calculate the day of the year that the current date is, and also consider the day of the week that January 1 of this year is, and then calculate it.
4. setDateStyle supports the input of a single date style and also supports the setting of multiple date styles. For style updates, arrays are mainly used to merge characters, and the indexOf method of strings is used to match and execute style settings.
5. CSS/JS/HTML are separated for easy maintenance. Function modularization facilitates reuse.

Copy code The code is as follows:

var logDateControl=(function(){
var curSelEl; //The currently selected date
var styleData=[],dataStyle={};
//Get the element with the specified id
var $=function(id){return document.getElementById(id)}
//Calculate the week of the specified date (default is the current date). This calculation method is more rigorous and accurate
var calWeek= function(dt){
var calDay=dt||new Date(); //The current time to be calculated
var firstDay=new Date(calDay.getFullYear(),0,1); //This year First day
//Calculate what day of the year it is now, 00:00 is the beginning of the day
var daysAll=Math.floor((calDay-firstDay)/1000/60/60/24) 1;
//What day of the week is the first day of the year
var firstDayWeekday=firstDay.getDay();
//The result is added to Monday of the first week to facilitate subsequent calculations
var diffDay=firstDayWeekday= =0?6:firstDayWeekday-1;
daysAll=daysAll diffDay;
return Math.ceil(daysAll/7); //Return the calculation result
}
//Calculate the number of days in a month, The year is 4 digits, the month is 1-2 digits (it should be in js date format such as 0 in January), the data is illegal and returns -1
var getDaysLen=function(year,month){
if(!( /^d{4}$/.test(year)&&/^d{1,2}$/.test(month))){return -1}
var monthDays=[31,28,31,30 ,31,30,31,31,30,31,30,31]
//Exists February 29th
if(month==1&&new Date(year,1,29).getMonth()== 1){monthDays[1]=29}
return monthDays[month]
}
//Display the date list, pass in the year and month (pass in the daily month.For example, February is passed in 2), and the display position
var displayDayList=function(year,month,pos){
var daysList=[];
var cells1=$(pos).rows[0] .cells;
var cells2=$(pos).rows[1].cells;
var daysArr=['日','一','二','三','四','五','六'];
//The following month-1 is converted to js month representation
for(var i=1,l=getDaysLen(year,--month) 1;i var wd=new Date(year,month,i).getDay();
cells1[i-1].className="";
if(wd==0||wd== 6){cells1[i-1].className="weekEnd";} //Add special style for weekends
//_oldCls saves the default style of the current date
cells1[i-1].innerText=daysArr[ wd];
cells2[i-1].className="unSelectDay";
cells2[i-1].setAttribute("_oldCls","unSelectDay");
cells2[i-1]. innerText=i>9?i:"0" i;
//Match user-defined style
var dtStr=year "|" (month 1) "|" i;
if((", " styleData.join(',') ",").indexOf("," dtStr ",")>-1){
cells2[i-1].className="unSelectDay " dataStyle[dtStr];
cells2[i-1].setAttribute("_oldCls","unSelectDay " dataStyle[dtStr]);
}
}
//If it is the current month, select the current day
if( new Date().getMonth()==month){
curSelEl=cells2[new Date().getDate()-1];
curSelEl.className="selectDay";
}
for(var j=i-1;j<31;j ){
cells1[j].className=cells2[j].className="";
cells1[j].innerHTML=cells2[j] .innerHTML=" "; , you can directly pass in the DOM element that saves the date content, or the function determines based on the click position
var changeInfo=function(e){
e=e||event;
var el=e.target|| e.srcElement||e; //The last e: may be the incoming object
var day=el.innerText;
if(!/^d{1,2}$/.test(day) ) return; //If it is not a date, do nothing
//Restore the style of the previously selected date
if(curSelEl){curSelEl.className=curSelEl.getAttribute("_oldCls")}
curSelEl=el ; //Save the currently processed element
//Update the style of the selected date
el.className="selectDay";
var dt=new Date($("year").value,$(" month").value-1,day);
//Update information
$("day").value=day; //Date
$("weekday").value=['day ','One','Two','Three','Four','Five','Six'][dt.getDay()]; //Day of the week
$("week").value= calWeek(dt); //Week of the week
}
//Initialization
window.attachEvent("onload",function(){
var curDate=new Date(),curYear=curDate. getFullYear();
//Display the upper and lower ten years
for(var i=-10;i<10;i ){$("year").add(new Option(curYear i,curYear i)) }
$("year").selectedIndex=10; //The current year is selected by default
$("month").selectedIndex=curDate.getMonth(); //The current month
$("day ").value=curDate.getDate(); //Current date
$("weekday").value=['日','一','二','三','四','五','Saturday'][curDate.getDay()]; //The current day of the week
$("week").value=calWeek(); //The current week
//Change the date or year Update date list
$("year").onchange=$("month").onchange=function(){displayDayList($("year").value,$("month").value,"daysList ")};
//Display a list of dates for the current month and highlight today's date
displayDayList(curDate.getFullYear(),curDate.getMonth() 1,"daysList");
});

//Interface for setting styles externally.
//Format: ([2007,10,12],"color:#f00") ([[2007,10,20],[2007,11,25]],"color:#00f")
//If the month is less than 10, do not bring 0
var setDateStyle=function(dateArr,style){
if(typeof dateArr!="object")return;
if(dateArr instanceof Array){
if(dateArr[0] instanceof Array){
for(var i=0;i }
var dataStr= dateArr.join('|');
styleData.push(dataStr);
dataStyle[dataStr]=style;
return;
}
}
//External interface
return {setDateStyle:setDateStyle}
})();
//Test style setting
logDateControl.setDateStyle([[2007,12,15],[2007,11,12]], "test");


[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute ]
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!