JavaScript-制作日历

JavaScript-制作日历

 

 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>制作日历</title>
    <style>
      table {
        width: 25%;
        height: 210px;
        float: left;
      }
      table th {
        background-color: grey;
        height: 25px;
      }
    </style>
  </head>
  <body>
    <script>
      function calendar(y) {
        let html = ""; // 代表日历输出内容的字符串
        // 确定y年的第1天时星期几
        let w = new Date(y, 0, 1).getDay();
        //  将0转换位7
        w = w == 0 ? 7 : w;
        // 输出12个月
        for (let m = 1; m <= 12; m++) {
          // 输出12个月的日历头,每行4个,设置样式
          html += "<table>";
          html += "<tr><th colspan=7>" + y + "年" + m + "月</th></tr>";
          html +=
            "<tr><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td><td>日</td></tr>";
          // 计算当月有多少天,通过将下个月的日期设置为0得到
          let max = new Date(y, m, 0).getDate();
          // 从当月第1天,循环当月最后1天
          // 开始新的一行
          html += "<tr>";
          for (let d = 1; d <= max; d++) {
            // 根据星期输出到行的对应位置
            if (d == 1 && w != 1) {
              // 填补当月第1天前面的空白
              html += "<td colspan=" + (w - 1) + "></td>";
            }
            html += "<td>" + d + "</td>";
            // 调整星期的值(1-7)
            w = w + 1 == 8 ? 1 : w + 1;
            // 根据当前d和w值的情况闭合tr标签
            if (d == max) {
              // 当月结束
              html += "</tr>";
            } else if (w == 1) {
              // 当周结束
              html += "</tr><tr>";
            }
          }
          html += "</table>";
        }
        return html;
      }
      let year = prompt("请输入四位年份:");
      // 应该判断year是否为4位整数
      document.write(calendar(year));
    </script>
  </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逆游古河而上

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值