制作完成效果图如下:时间会实时更新
制作步骤一(HTML):
<div class="container">
<span id="hours">00</span> :
<span id="minute">00</span> :
<span id="second">00</span>
</div>
<div class="btngroup">
<button id="start">开始</button>
<button id="stop">暂停</button>
</div>
制作步骤二(CSS):
*{
margin: 0;
padding: 0;
}
body{
background: #000;
color: #fff;
}
.container{
margin: 100px auto;
text-align: center;
font-size: 12rem;
font-weight: 300;
}
.container span{
display: inline-block;
width:200px;
}
.btngroup{
text-align: center;
}
.btngroup button{
margin: 0px 10px;
padding: 30px 100px;
border:none;
border-radius: 5px;
font-size: 2rem;
color:#fff;
cursor: pointer;
outline: none;
}
.btngroup button:first-child{
background: #00aaff;
}
.btngroup button:last-child{
background: #ffb200;
}
制作步骤三(JavaScript):
window.onload=function(){//页面加载事件
// var timer=setInterval(function(){
// showtime();
// },1000);
var start=document.getElementById("start");
start.onclick=function(){
var timer=setInterval(function(){
showtime();
},1000);//1000==1秒,方法延迟1s后执行
}
var stop=document.getElementById("stop");
stop.onclick=function(){
clearInterval(timer);//清除定时器
}
}
function showtime(){
var time=new Date();//通过构造函数创建Date方法
var hours=time.getHours();//小时
var minute=time.getMinutes();//分钟
var second=time.getSeconds();//秒数
//当时间<=9就在前面添加0
hours=hours<=9?"0"+hours:hours;//条件运算符,如果条件成立则执行A语句:不成立则执行B语句
minute=minute<=9?"0"+minute:minute;
second=second<=9?"0"+second:second;
document.getElementById("hours").innerHTML=hours;
document.getElementById("minute").innerHTML=minute;
document.getElementById("second").innerHTML=second;
//属性设置或返回元素的innerHTML
}
谢谢观赏,如有不足希望指出,我定虚心请教
如有疑问,请发私信(每天不定时间回复)