1. 程式人生 > >【HTML+CSS+JavaScript】日歷生成器

【HTML+CSS+JavaScript】日歷生成器

itl you ava lse max 星期幾 mat mar 超出

需求:實現日歷生成器

技術分享圖片

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>同誌交友</title>
    <style>
        input {
            width: 50px;
            padding: 10px;
            font-size: 16px;
            border: 1px solid #ccc;
        }
        select 
{ width:100px; padding:10px; } button { padding: 10px 20px; border: 1px solid #ccc; background: #f5f5f5; cursor: pointer; } #res { margin-top:20px; } #res table { width
: 700px; table-layout: fixed; border-collapse: collapse; } #res td,#res th { padding: 10px; border: 1px solid #999; text-align: center; } .red { color: red; } .green { color
: green; } </style> </head> <body> <h1>日歷生成器</h1> <hr> 請輸入本月多少天: <input type="number" id="days" max="31" min="28" step="1" value="31"> 請輸入本月一號星期幾: &nbsp;&nbsp;&nbsp; <select id="weekday"> <option value="0">星期日</option> <option value="1">星期一</option> <option value="2">星期二</option> <option value="3">星期三</option> <option value="4">星期四</option> <option value="5">星期五</option> <option value="6">星期六</option> </select> &nbsp;&nbsp;&nbsp; <button onclick="makeCalendar()">生成日歷</button> <div id="res"></div> <script> //聲明函數 function makeCalendar() { //獲取 每月天數 var days = Number(document.getElementById(days).value); //獲取一號是星期幾 var weekday = Number(document.getElementById(weekday).value); //計算日歷有多少行 var rows = Math.ceil((days + weekday) / 7); //定義變量 var html = <table>; html += ` <tr> <th class="red">星期日</th> <th>星期一</th> <th>星期二</th> <th>星期三</th> <th>星期四</th> <th>星期五</th> <th class="green">星期六</th> </tr> `; var dayNumber = ‘‘; //循環 生成表格 for (var i = 0; i < rows; i ++) { html += <tr>; for (j = 1; j <= 7; j ++) { if (j === 1) { html += <td class="red">; } else if (j === 7) { html += <td class="green">; } else { html += <td>; } dayNumber = j + i*7 - weekday; //計算每個單元格的數值 //判斷是否超出範圍 if (dayNumber <= 0 || dayNumber > days) { dayNumber = ‘‘; } html += dayNumber+</td>; } html += </tr>; } html += </table> //添加表格內容到頁面 document.getElementById(res).innerHTML = html; } </script> </body> </html>

【HTML+CSS+JavaScript】日歷生成器