В современную цифровую эпоху веб-разработка является универсальным и полезным навыком. Чтобы начать ваше путешествие, мы собираемся создать простое, но функциональное веб-приложение «Калькулятор возраста», используя триумвират веб-разработки: HTML, CSS и JavaScript. Это приложение позволит пользователям легко определять свой возраст по дате рождения. Итак, засучите рукава и давайте погрузимся в это практическое руководство!
Установка основы с помощью HTML
Как и в любом проекте по веб-разработке, мы начнем с создания основы с использованием HTML. Ниже приведена структура 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>Age-Calculater</title> <link rel="stylesheet" href="style.css"> <link href="https://fonts.googleapis.com/css2?family=Estonia&family=Vast+Shadow&display=swap" rel="stylesheet"></head> <body> <div class="container"> <h1>Age Calculator</h1> <div class="form"> <label for="birthday">Enter your Birthday</label> <input type="date" name ="birthday" id ="birthday"> <button id="btn"></button> <p id="result">Your age is 21 years old</p> </div> </div> <script src ="index.js"></script> </body> </html>
Добавляем стиль с помощью CSS
Привлекательный дизайн повышает удобство использования. Наши стили CSS вдохнут жизнь в приложение «Калькулятор возраста», сделав его визуально привлекательным и простым в использовании. Вот пример того, как вы можете стилизовать свое приложение:
body { margin:0; background-image: url("image1.jpg"); background-size: cover; background-repeat: no-repeat; background-position: center center; background-color:rgb(255, 255, 255); } .container { background-color: rgba(255, 255, 255, 0.8); box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.9); width: 100%; max-width: 600px; margin: auto; margin-top: 150px; padding: 10px; border-radius: 50px; border: 2px black solid; } h1 { text-align: center; font-weight: bold; color: rgb(90, 10, 10); font-family: "Vast Shadow", sans-serif; /* text-transform: uppercase; */ } .form { display: flex; flex-direction: column; align-items: center; margin-bottom: 20px; } label { margin-bottom: 20px; font-family: "Estonia", sans-serif; color: rgb(90, 10, 10); font-size: 50px; } input { margin-bottom: 20px; font-family: 'Courier New', Courier, monospace, sans-serif; color: rgb(90, 10, 10); font-size: 20px; } button { background-image: url("age-icon.svg"); background-color: rgba(255, 255, 255, 0.1); background-repeat: no-repeat; background-size: contain; background-position: center center; width: 100%; max-width: 200px; height: 50px; border: none; /* margin-bottom: 1px; */ transition: background-image 0.3 ease; } button:hover { border-radius: 5px; box-shadow: 0 0 10px rgb(0, 0, 0, 0.2); } #result { font-family: "Estonia", sans-serif; color: rgb(90, 10, 10); font-size: 50px; }
Магия JavaScript
Теперь самое интересное — добавление функциональности с помощью JavaScript! Код JavaScript позволит пользователям вводить дату своего рождения и рассчитывать свой возраст. Взгляните на код JavaScript ниже:
const btn = document.getElementById("btn"); const birthday = document.getElementById("birthday"); const result = document.getElementById("result"); function calculateAge() { const birthdayValue = birthday.value; if (birthdayValue ==="") { alert("Please enter your Birthdate"); } else { const age=getAge(birthdayValue); result.innerText=`Your age is ${age} ${age < 1 ? "year" : "years"} old`; } } function getAge(birthdayValue){ const currentDate= new Date(); const birthdate = new Date(birthdayValue) let age=currentDate.getFullYear()-birthdate.getFullYear(); let month=currentDate.getMonth()-birthdate.getMonth(); if(month < 0 || (month===0 && currentDate.getDate() < birthdate.getDate())) { age--; } return age; } btn.addEventListener("click", calculateAge)
Собираем все вместе
Прелесть этого проекта в его универсальности. Вы можете настроить дизайн приложения, изменить вычисления JavaScript или даже расширить его функциональность. Этот проект служит отличной отправной точкой для дальнейшего изучения мира веб-разработки.
GitHub: — https://github.com/bhageshwaree11