您的位置:首页 > Web前端 > JavaScript

JavaScript实现计时器,一个按钮实现开始和停止的功能

2018-02-03 15:50 696 查看
<!DOCTYPE html>

<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
var intervalId;
var i = 0;
var count=0;
function startTime(){
var hour = document.getElementById("hour");
var minute = document.getElementById("minute");
var second = document.getElementById("second");
var ms = document.getElementById("ms");
var buttonEle = document.getElementById("start");

if(i%2==0){
buttonEle.innerHTML="暂停计时";
intervalId = setInterval(function(){
count += 1;
var thehour=parseInt(count/360000);
var theminute=parseInt(count/6000%60);
var thesecond=parseInt(count/100%60);
var thems = parseInt(count%100);

if(thehour>=10){
hour.innerHTML=thehour+" ";
}
else{
hour.innerHTML="0"+thehour+" ";
}

if(theminute>=10){
minute.innerHTML=theminute+" ";
}
else{
minute.innerHTML="0"+theminute+" ";
}

if(thesecond>=10){
second.innerHTML=thesecond+" ";
}
else{
second.innerHTML="0"+thesecond+"  ";
}
if(thems>=10){
ms.innerHTML=thems+" ";
}
else{
ms.innerHTML="0"+thems+" ";
}
},10)
}
else{
buttonEle.innerHTML="开始计时";
clearInterval(intervalId);
}
i++;
}
</script>
<style type="text/css">
body,html{
background: violet;
/*position: relative;*/
}
#firstDiv{
height: 50%;
width:50% ;
position:absolute;
margin-left: 350px;
margin-top:150px;
background: #ffcccc;
}
#twoDiv{
height: 200px;
width:100%;
position: absolute;
margin-top: 130px;
margin-left: 130px;;
}
span{
font-size: 30px;
}
button{
font-size: 20px;
}
</style>
</head>
<body>
<div id="firstDiv">
<div id="twoDiv">
<span><span id="hour">00 </span>时</span>
<span><span id="minute">00 </span>分</span>
<span><span id="second">00 </span>秒</span>
<span><span id="ms">00 </span>毫秒</span>

<button id="start" onclick="startTime()">开始计时</button>
</div>
</div>
</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐