利用HTML实现秒表功能

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Title</title>

<style>

.a{

background-image: url(https://pic.616pic.com/ys_bnew_img/00/44/96/SrHNIPCVGH.jpg);

width: 500px;

height: 500px;

/* border: 1px solid rgb(0, 255, 157); */

position:absolute;

left: 50%;

margin-left: -400px;

text-align: center;

line-height: 100px;

}

#showTime

{

margin-top: 200px;

margin-left: 100px;

color: rgb(1, 7, 12);

text-align: center;

width: 300px;

height: 60px;

font-size: 60px;

}

#startBn{

width: 60px;

height: 30px;

/* margin-top: 300px; */

}

#restBn{

width: 60px;

height: 30px;

}

</style>

</head>

<body>

<div class="a">

<div id="showTime">00:00:00</div>

<button id="startBn">启动</button>

<button id="restBn">复位</button>

</div>

<script>

//------------------

var time,showTime,startBn,restBn,pauseDate;

//布尔开关

var bool=false;

//暂停的累计时间

var pauseTime=0;

init();

function init() {

showTime=document.getElementById("showTime");

startBn=document.getElementById("startBn");

restBn=document.getElementById("restBn");

startBn.addEventListener("click",clickHandler);//开始按钮 ~ 暂停按钮

restBn.addEventListener("click",clickHandler);//复位按钮

setInterval(animation,16);

}

//转化时间函数

function animation() {

if(!bool) return;

//前时间减去上次开启时间减去暂停累计时间

var times=new Date().getTime()-time-pauseTime;

var minutes=Math.floor(times/60000);//毫秒转化为分钟

var seconds=Math.floor((times-minutes*60000)/1000);//已知分钟

// 将time减去分钟 除去1000得出 秒

var ms=Math.floor((times-minutes*60000-seconds*1000)/10);//

showTime.innerHTML=

(minutes<10 ? "0" +minutes : minutes)+":"

+(seconds<10 ? "0"+seconds :seconds)+":"

+(ms<10 ? "0"+ms : ms);

}

//点击时的事件

function clickHandler(e) {

e= e || window.event;

if(this===startBn){

bool=!bool;

if(bool){

this.innerHTML="暂停";

//如果我们上一次暂停时间是空,表示没有暂停过,因此,直接返回0

//如果上次的暂停时间是有值得,用当前毫秒数减去上次的毫秒数,这样就会得到暂停时间

pauseTime+=(!pauseDate ? 0 : new Date().getTime()-pauseDate);

if(time) return;

time=new Date().getTime();

return;//是为bool判断跳出

}

this.innerHTML="启动";

pauseDate=new Date().getTime();

return;//是为this是否等于startBn判断跳出

}

startBn.innerHTML="启动";

pauseTime=0;

pauseDate=null;

bool=false;

time=0;

showTime.innerHTML="00:00:00";

}

</script>

</body>

</html>

相关推荐
旧曲重听136 分钟前
最快实现的前端灰度方案
前端·程序人生·状态模式
默默coding的程序猿1 小时前
3.前端和后端参数不一致,后端接不到数据的解决方案
java·前端·spring·ssm·springboot·idea·springcloud
夏梦春蝉1 小时前
ES6从入门到精通:常用知识点
前端·javascript·es6
归于尽1 小时前
useEffect玩转React Hooks生命周期
前端·react.js
G等你下课1 小时前
React useEffect 详解与运用
前端·react.js
我想说一句1 小时前
当饼干遇上代码:一场HTTP与Cookie的奇幻漂流 🍪🌊
前端·javascript
funnycoffee1231 小时前
Huawei 6730 Switch software upgrade example版本升级
java·前端·华为
小鱼小鱼干1 小时前
【Tauri】Tauri中Channel的使用
前端
拾光拾趣录1 小时前
CSS全面指南:从基础布局到高级技巧与实践
前端·css
南屿im1 小时前
基于 Promise 封装 Ajax 请求:从 XMLHttpRequest 到现代化异步处理
前端·javascript