利用js製作簡單的動態日曆

mj_hoe發表於2020-12-27

利用js製作簡單的動態日曆

程式碼


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .calendar{
            position:absolute;
            left: 50%;
            top: 50%;
            margin: -300px 0 0 -400px;
            width: 800px;
            height: 600px;
            background: rgba(0,0,0,0.2);
        }
        .item{
            display: inline-block;
            width: 80px;
            height: 80px;
            line-height: 80px;
            text-align: center;
            background:#3498db;
            color:#fff;
            border:1px solid rgba(255,255,255,0.2);
            transition: all .5s;
        }
        .item:hover{
            background: #2980b9;
            transform: scale(1.1);
        }
    </style>
</head>
<body>

    <div class="calendar">
        <script>
            var year = 2020;
            var month = 12;
            //從1900年1月1日到當前年份月份上一個月的總天數
            var totalDays = 0;
            //目標月份的總天數
            var days = 0;
            //宣告輸出日曆前需要保留的空格數
            var space = 0;

            //統計整年的總天數
            for(var i = 1900;i<year;i++){
                totalDays += (i % 4 == 0 && i % 100 != 0) || i  % 400 == 0 ? 366 : 365;
            }
            //統計整月的總天數
            for(var i = 1;i<month;i++){
                switch(i){
                    case 4:
                    case 6:
                    case 9:
                    case 11:
                        totalDays += 30;
                        break;
                    case 2:
                        totalDays += (year % 4 == 0 && year % 100 != 0) || year  % 400 == 0 ? 29 : 28;
                        break;
                    default:
                        totalDays += 31;
                }
            }
            //計算空格數
            space = totalDays % 7;
            //獲取目標月份的總天數
            switch(month){
                case 4:
                case 6:
                case 9:
                case 11:
                    days = 30;
                    break;
                case 2:
                    days = (year % 4 == 0 && year % 100 != 0) || year  % 400 == 0 ? 29 : 28;
                    break;
                default:
                    days = 31;
            }
            //計數器
            var count = 0;
            for(var i = 0 ;i < space;i++){
                count++;
                document.write('<div class="item" style="visibility: hidden"></div>');
            }
            //display:none       隱藏元素的同時不佔用位置
            //visibility:hidden  隱藏元素的同時佔用位置
            for(var i = 1;i <= days;i++){
                count++;
                document.write(`<div class="item">${i}</div>`);
                if(count == 7){
                    document.write('<br>');
                    count = 0;
                }
            }
        </script>
    </div>

</body>
</html>

相關文章