用 html, css, js 实现秒表

最终实现效果如下:
在这里插入图片描述

html 文件

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>秒表</title>
    <link rel="stylesheet" href="./css/style.css">
</head>

<body>
    <div id="bor">
        <div id="show">
            00:00:00        
        </div>
        <div id="btnWarp">
            <button id="start">开始</button>
            <button id="stop">暂停</button>
            <button id="reset">复位</button>
        </div>
    </div>

    <script src="./src/sw.js"></script>
</body>

</html>

css 文件

#bor {
    width: 200px;
    height: 300px;
    margin: auto;
    margin-top: 100px;
    border: black solid 1px;
    background-color: cornflowerblue;
}

#show {
    width: 100px;
    line-height: 40px;
    margin: 40px auto;
    /*background-color: blueviolet;*/
    text-align: center;
    font-size: larger;
}

#start,#reset,#stop{
    width: 100px;
    height: 30px;
    margin: 10px;
    color: white;
    border-color: wheat;
    background-color: black;
}

#btnWarp {
    text-align: center;
}

js 文件

function $(something) {
    return document.querySelector(something);
}

let i = 0;
let isCounting = false;
let time = $('#show');
let intervalID = undefined;

let double = function (m) {
    return m < 10 ? `0${m}` : `${m}`;
}

let show = function (t, sh) {
    t.innerHTML = sh + '';
}

let showTime = function (n) {
    const hour = parseInt(n / 360);
    const min = parseInt(n / 60) % 60;
    const sec = n % 60;
    return `${double(hour)}:${double(min)}:${double(sec)}`;
}

$('#start').onclick = function () {
    if (isCounting) {
        return
    }
    isCounting = true;
    intervalID = setInterval(function () {
        i++;
        show(time, showTime(i));
    }, 1000);
}

$('#stop').onclick = function () {
    isCounting = false;
    clearInterval(intervalID);
}

$('#reset').onclick = function () {
    isCounting = false;
    clearInterval(intervalID);
    i = 0;
    show(time, showTime(i));
}

猜你喜欢

转载自blog.csdn.net/Web_blingbling/article/details/107685983
今日推荐