这是简单的正计时,mark一下,
效果图如下:
因为没有考虑到浏览器后台会自动失去cpu的权限,所以会自动暂停计时,因而下面这个代码存在问题,但可留待以后解决,先mark下。同时升级新的逻辑算法来实现该问题。具体转到该链接:升级版
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>时间使用</title>
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
.container {
width: 90%;
height: 100%;
margin: 0px auto;
padding: 0px;
text-align: center;
clear:both;
}
.item {
position: relative;
top: 35%;
text-align: center;
}
button {
position: relative;
}
span {
font-size: 8vw;
}
</style>
<script type="text/javascript">
function dateconvert(i) {
if (i < 10) {
return i = "0" + i;
} else {
return i = "" + i;
}
}
function countdown(start,lastlefttime) {
var end = new Date().getTime();
var leftTime = start + lastlefttime;
var minute = parseInt(leftTime / 60);
var second = parseInt(leftTime % 60);
document.getElementById("m").innerText = this.dateconvert(minute);
document.getElementById("s").innerText = this.dateconvert(second);
return leftTime;
}
window.onload = function () {
document.getElementById("m").innerText = this.dateconvert(0);
document.getElementById("s").innerText = this.dateconvert(0);
var lastleftTime = 0;
var s = document.getElementById("start");
var c;
s.onclick = function () {
var start = 1;
var temp = lastleftTime;
if (s.innerText == "暂停") {
clearInterval(c);
s.innerText = "开始";
} else {
c = setInterval(function () {
lastleftTime = countdown(start,temp);
start++;
}, 1000);
s.innerText = "暂停";
}
};
var r = document.getElementById("reset");
r.onclick = function () {
clearInterval(c);
document.getElementById("m").innerText = window.dateconvert(0);
document.getElementById("s").innerText = window.dateconvert(0);
lastleftTime = 0;
start = 0;
s.innerText = "开始";
};
};
</script>
</head>
<body>
<div class="container">
<div class="item">
<span id="m"></span><span>:</span>
<span id="s"></span>
</div>
<button id="start">开始</button>
<button id="reset">重置</button>
</div>
</body>
</html>