开发工具与关键技术: Adobe Dreamweaver CC 2019
撰写时间:2021/5/8
效果图:
HTML:
<body>
<div class="contain">
<span id="Interval">10:38:00</span>
</div>
<div class="box">
<button id="pause">暂停</button>
<button id="action">开始</button>
</div>
</body>
CSS部分:
<style>
.contain{
width: 200px;
height: 50px;
background: #0FD2F0;
border-radius: 20px;
font-weight: bold;
color: #fff;
text-align: center;
font-size: 30px;
line-height: 50px;
margin: 100px auto;
}
.box{
margin: -100px 45%;
}
#pause{
margin-left: 30px;
}
</style>
JS部分:
<script>
//获取日期对象
function getDate(){
dobj=new Date();
hour = dobj.getHours(); //时
minute=dobj.getMinutes(); //分
second = dobj.getSeconds();//秒
str=addZero(hour)+":"+addZero(minute)+":"+addZero(second);
dsq=document.getElementById("Interval");//获取id Interval
dsq.innerHTML=str;
}
//未点击按钮前,先执行一次
getDate();
start();
//开始函数
function start(){
sobj=setInterval(getDate,1000); //设置定时器,一秒钟执行一次getDate()
}
//停止函数
function stop(){
clearInterval(sobj); //清除定时器
}
//关闭按钮
c = document.getElementById("pause");
c.onclick=function(){
stop();
}
//开始按钮
action = document.getElementById("action");
action.onclick=function(){
start();
}
//数值只有个位数时,前面补0
function addZero(n){
return n<10?"0"+n:n;
}
</script>