+1

Tạo đồng hồ đếm ngược đơn giản bằng HTML, CSS và JavaScript

Xây dựng bộ đếm thời gian là một cách tuyệt vời để hiểu sự tương tác giữa HTML, CSS và JavaScript. Bài đăng này sẽ hướng dẫn bạn quy trình tạo bộ đếm thời gian đơn giản bắt đầu đếm khi người dùng nhấp vào nút. Bộ đếm thời gian sẽ hiển thị thời gian đã trôi qua theo giờ, phút và giây.

1. Cấu trúc HTML

Để tạo một đồng hồ đếm ngược hiển thị thời gian trôi qua tính bằng giờ, phút và giây, chúng ta cần kết hợp HTML, CSS và Javascript một cách khéo léo. Đầu tiên, bạn cần tạo cấu trúc HTML cơ bản cho đồng hồ đếm ngược. Hãy sử dụng thẻ "div" để hiển thị đồng hồ và một nút "button" để bắt đầu. Bạn có thể tham khảo đoạn mã HTML mẫu dưới đây:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Timer Counter</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h1>Timer Counter</h1>
        <div id="timer">00:00:00</div>
        <button id="startButton">Start Timer</button>
    </div>
    <script src="script.js"></script>
</body>
</html>

Trong đoạn mã này, thẻ "div" với id="timer" sẽ hiển thị đồng hồ và thẻ "button" với id="startButton" sẽ được sử dụng để khởi động đồng hồ.

2. Tạo kiểu CSS

Tiếp theo, chúng ta cần tạo lớp vỏ bên ngoài (skin) cho đồng hồ bằng cách sử dụng CSS. Bạn có thể tự do thiết kế giao diện theo sở thích của mình. Dưới đây là một ví dụ để bạn tham khảo:

/* styles.css */
body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #f0f0f0;
}

.container {
    text-align: center;
}

#timer {
    font-size: 3rem;
    margin-bottom: 20px;
}

button {
    padding: 10px 20px;
    font-size: 1rem;
    cursor: pointer;
}

Đoạn mã CSS này sẽ giúp căn giữa nội dung theo cả chiều ngang và chiều dọc, tạo kiểu cho đồng hồ với cỡ chữ lớn và thêm phần đệm cũng như tạo kiểu cho nút để dễ dàng nhấp chuột hơn.

3. Thêm chức năng trong JavaScript

Cuối cùng, hãy thêm Javascript để xử lý chức năng của đồng hồ. Điều này bao gồm việc khởi động đồng hồ khi nhấp vào nút "Start", cập nhật thời gian mỗi giây và hiển thị thời gian đã trôi qua.

// script.js
document.addEventListener("DOMContentLoaded", () => {
    const startButton = document.getElementById("startButton");
    const timerDisplay = document.getElementById("timer");
    let timerInterval;
    let startTime;

    function startTimer() {
        startTime = new Date();
        timerInterval = setInterval(updateTimer, 1000);
    }

    function updateTimer() {
        const currentTime = new Date();
        const elapsedTime = new Date(currentTime - startTime);

        const hours = String(elapsedTime.getUTCHours()).padStart(2, '0');
        const minutes = String(elapsedTime.getUTCMinutes()).padStart(2, '0');
        const seconds = String(elapsedTime.getUTCSeconds()).padStart(2, '0');

        timerDisplay.textContent = `${hours}:${minutes}:${seconds}`;
    }

    startButton.addEventListener("click", startTimer);
});

Đoạn mã Javascript này sẽ chờ DOM được tải xong, sau đó xác định hàm "startTimer" để khởi tạo thời gian bắt đầu và đặt khoảng thời gian cập nhật đồng hồ mỗi giây. Hàm "updateTimer" sẽ tính toán thời gian đã trôi qua, định dạng và cập nhật hiển thị trên đồng hồ. Cuối cùng, đoạn mã thêm một trình lắng nghe sự kiện vào nút để bắt đầu đồng hồ khi nhấp vào.

Ngoài ra, bạn có thể ẩn nút "Start" và hiển thị nút "Stop" bằng cách bổ sung đoạn mã Javascript sau:

// script.js
document.addEventListener("DOMContentLoaded", () => {
    const startButton = document.getElementById("startButton");
    const stopButton = document.getElementById("stopButton");
    const timerDisplay = document.getElementById("timer");
    let timerInterval;
    let startTime;

    function startTimer() {
        startTime = new Date();
        timerInterval = setInterval(updateTimer, 1000);
        startButton.style.display = "none";
        stopButton.style.display = "inline-block";
    }

    function stopTimer() {
        clearInterval(timerInterval);
        startButton.style.display = "inline-block";
        stopButton.style.display = "none";
    }

    function updateTimer() {
        const currentTime = new Date();
        const elapsedTime = new Date(currentTime - startTime);

        const hours = String(elapsedTime.getUTCHours()).padStart(2, '0');
        const minutes = String(elapsedTime.getUTCMinutes()).padStart(2, '0');
        const seconds = String(elapsedTime.getUTCSeconds()).padStart(2, '0');

        timerDisplay.textContent = `${hours}:${minutes}:${seconds}`;
    }

    startButton.addEventListener("click", startTimer);
    stopButton.addEventListener("click", stopTimer);
});

Hy vọng bạn thấy bài viết này thú vị.


All Rights Reserved

Viblo
Let's register a Viblo Account to get more interesting posts.