Results the preview


















































































A variety of products emerge in endlessly, the company level strictly grasp the product style, seeking to stand out in the design, which increases the difficulty of front-end development, customized scene more and more common component library has been unable to meet our needs, feel the time to strengthen the ability to this aspect ~~

Implementation approach

  • Figure out what day of the week the first day of the month starts on.
  • Encapsulate a function that calculates the number of days in a month based on the year and month, and splices it with the front blank.
  • Calendar has two modes, radio and start – end, according to the different parameters passed in to select different modes, processing.
  • When the number is selected, the number greater than the current number cannot be selected, either year or month. For example: today is the 23rd, anything greater than 23rd cannot be selected.

The event processing

Entry function:

$(function(){
    
    function init() {
        ChangeData();   // Count the number of days in the month
        render();       // Render the page
        bindEvent();    // Initialize the event binding} init(); }) (document)
Copy the code

The execute now function +init is used for many plugins such as new swiper().init().

function ChangeData() {
        // Get the number of days in a month
        days = getMonthDay( year, month );
        // Create the number of days in the current month
        daysArr = generateArray( 1, days );
        // The number of pre-blank parts
        weekday = getweekday( year, month );
        // A collection of pre-blank sections
        weekdayArr = generateArray( 1, weekday );
        // The current date
        showTitle = `${year}years${month}Month `
    }
Copy the code

Switching month events:

function changeMonthHandler( isAdd, callback ) {
    // isAdd is 1 for forward and 0 for backward
    if ( isAdd === '1' ) {
        month += 1;
        let Year = month > 12 ? year + 1 : year;
        if ( !checkRange( Year ) ) {
            month = month > 12 ? 1: month; year = Year; _obj.month = month; _obj.year = Year; ChangeData(); callback(_obj); }}else {
        month -= 1;
        let Year = month < 1 ? year - 1 : year;
        if ( !checkRange( Year ) ) {
            month = month < 1 ? 12: month; year = Year; _obj.month = month; _obj.year = Year; ChangeData(); callback(_obj); }}}// Determine if the year passed is out of bounds
function checkRange( year ) {
    let overstep = false;
    if ( year < minYear || year > maxYear ) {
        overstep = true;
    }
    return overstep;
}

Copy the code

The child triggers the parent event and passes forward or backward flags and callbacks. Forward is month +1, and determines whether the current month is more than 12. If it is more than 12, the year is +1, and a ChangeData event is triggered to recalculate the number of days in the month.

Radio click events:

function openDisAbled( day, callback ) {
        let bool = true;
        if ( day == ' ' ) return bool;
        
        let date = `${year}/${month}/${day}`;
        // Minimum date limit
        let minTime = `${min.year}/${min.month}/${min.day}`;
        // Maximum date limit
        let maxTime = `${max.year}/${max.month}/${max.day}`;
        // The current date conversion timestamp
        let timestamp = new Date(date).getTime();
        // If the date clicked is executed within this month
        if ( timestamp >= new Date(minTime).getTime() && timestamp <= new Date(maxTime).getTime() ) {
            bool = false;
        }
        callback( bool, _obj );
    }
Copy the code

The child clicks to trigger the parent event to pass in the number and callback. The front blank part is empty, so if it is equal to empty, it cannot be clicked directly. The code above determines whether the date is selectable, such as next month’s date, which I cannot select. If the current date is expected to be greater than the minimum date and the current date is less than the maximum date then bool is set to false, callback back to the child, and can be clicked. The default value for minTime is 1950 and the maximum value for maxTime is 2050

Sub-level receiving for processing:

selectTime( el ) {
    let day = $(el).attr('index');
    ScreenAbled( 'section', { day }, ( res, { mode }) = > {
        // Exit if bool returns true
        if ( res ) return;
        // date Indicates an option mode
        if ( mode === 'date' ) {
            $(el)
                .addClass('active')      // Select add highlight style
                .siblings('.active')     // Filter out the sibling elements with active
                .removeClass('active');  // Delete the active class
                // Trigger a parent event to write the selected date
                ScreenAbled('alone', { day: day }); }})}Copy the code

Start-end event:

  • The parent
function ChangeDouble( callback, day ) {
        let date = `${year}-${month}-${day}`;
        // startDate Start time of storage
        let compare = new Date(date.replace(/\-/g.'/')).getTime() < new Date( startDate.replace(/\-/g.'/') ).getTime()
        if ( isStart || compare ) {
            startDate = date;
            isStart = false;
            callback( 'start' );
            startTime = `${year}-${month}-${day}`;
        } else {
            isStart = true;
            callback( 'end' );
            endTime = `${year}-${month}-${day}`; }}Copy the code

Compare is used to screen out cases where the end time is longer than the start time, such as: start 5/23 and end 5/13. If this case is not true, the operator needs to select a new time.

  • The child
// Trigger the parent event
ScreenAbled( 'ChangeDouble', { day }, type= > {
    // Start time processing
    if ( type === 'start' ) {
        // Get all the elements of the small text to reset
        $('.seat').find('.slot').text(' ');
        // Add a small prompt for the currently clicked element
        $(el).find('.slot').text('start');
        
        $(el)
            .addClass('active')    // Add highlighting to the currently selected element
            .siblings('.active')   // Filter out elements with active
            .removeClass('active') // Delete the active class

        $(el)            
            .siblings('.section')   // Filter out elements with sections
            .removeClass('section') // Delete the section class
            
        // Store the starting subscript
        CollectIndex = day;
        return false;
    }
    // End time processing
    $(el)
        .addClass('active')      // Add a highlight style
        .siblings('.sign')       // Filter out the element with sign
        .slice( CollectIndex, day - 1 )   // Filter out elements in the start-end date range
        .addClass('section')              // Add highlighting styles to the elements of this range

    $(el).find('.slot').text('the end');
});
Copy the code

The operator needs to be prompted in small print inside the box when selecting the start and end, and the sub-processing is to add and remove styles dynamically.

Finally:

In the future, when there is a customized demand, close your eyes and think for a moment, and immediately give the person who is making the demand a shoulder fall and a set of military punch, so that he can not work this demand need not be engaged, haha. The above only illustrates the more important several functions of the complete source code in this thank you for reading, I hope to see you can harvest! Please give me a thumbs-up if you think it is useful. Your thumbs-up is the biggest motivation for my creation