【每日一练】214—年龄计算器

每日一练1年前 (2023)发布 admin
1,512 0

第214练的最终效果:

【每日一练】214—年龄计算器

完整的实现代码:

HTML:

<!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>214练-年龄计算器</title>
    <link rel=”stylesheet” href=”index.css”>
</head>
<body>
    <div class=”container”>
        <h1>年龄计算器</h1>
        <div class=”form”>
            <label for=”birthday”>输入您的出生年月日</label>
            <input type=”date” id=”birthday” name=”birthday”>
            <button id=”btn”>开始计算</button>
            <p id=”result”>你的年龄是…</p>
        </div>
    </div>
    <script src=”index.js”></script>
</body>
</html>

CSS:

body {
    margin: 0;
    padding: 20px;
    font-family: “Montserrat”, sans-serif;
    background-color: #f7f7f7;
  }
  .container {
    background-color: white;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    padding: 20px;
    max-width: 600px;
    margin: 0 auto;
    border-radius: 5px;
    margin-top: 50px;
  }
  h1 {
    font-size: 36px;
    text-align: center;
    margin-top: 0;
    margin-bottom: 20px;
  }
  .form {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  label {
    font-weight: bold;
    margin-bottom: 10px;
  }
  input {
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 5px;
    width: 100%;
    max-width: 300px;
  }
  button {
    background-color: #007bff;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    margin-top: 10px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }
  button:hover {
    background-color: #0062cc;
  }
  #result {
    margin-top: 20px;
    font-size: 24px;
    font-weight: bold;
  }

JS:

const btnEl = document.getElementById(“btn”);
const birthdayEl = document.getElementById(“birthday”);
const resultEl = document.getElementById(“result”);
function calculateAge() {
  const birthdayValue = birthdayEl.value;
  if (birthdayValue === “”) {
    alert(“请输入您的出生年月日”);
  } else {
    const age = getAge(birthdayValue);
    resultEl.innerText = ` ${age} ${age > 1 ? “岁” : “year”} `;
  }
}
function getAge(birthdayValue) {
  const currentDate = new Date();
  const birthdayDate = new Date(birthdayValue);
  let age = currentDate.getFullYear() – birthdayDate.getFullYear();
  const month = currentDate.getMonth() – birthdayDate.getMonth();
  if (
    month < 0 ||
    (month === 0 && currentDate.getDate() < birthdayDate.getDate())
  ) {
    age–;
  }
  return age;
}
btnEl.addEventListener(“click”, calculateAge);
© 版权声明

相关文章

暂无评论

暂无评论...