1、编写程序,实现电子时钟自动走动的效果,并提供一个按钮控制电子时钟是否停止走动。
<style>
.box{
width: 600px;
height: 200px;
margin: 20px auto;
line-height: 150px;
text-align: center;
}
#clock{
width: 400px;
height: 150px;
border: 1px solid rgb(75, 74, 74);
font-size: 50px;
font-weight: 700px;
}
</style>
<body>
<div class="box">
<div id="clock"></div>
<p>
<button id="btn_start">开始</button>
</p>
</div>
<script>
//1.创建变量
let timer = null; //定时器变量
let flag = true; //标记变量:用来标识当前按钮是“开始”还是“暂停”
showTime()
//2.定义函数:用于显示时间
function showTime(){
//创建日期对象---当前日期
let now = new Date()
//取出日期对象的时间
let h = now.getHours()
let m = now.getMinutes()
let s= now.getSeconds()
h = h<10? '0'+ h : h
m = m<10? '0'+ m : m
s = s<10? '0'+ s : s
//把时间放到页面div里
document.getElementById('clock').innerHTML = h + ':' + m + ':' + s
}
//3.给按钮注册click事件,在事件的处理程序中创建定时器
let start = document.getElementById('btn_start')
start.addEventListener('click',function(){
//判断标记变量flag 若为true表示时间正在运行,按钮显示“暂停”
if(flag){
timer = setInterval(showTime,1000) //创建定时器
flag = ! flag //取反
this.innerHTML = '暂停' //this代表的是当前的按钮start
}else{
clearInterval(timer) //清除定时器
flag = ! flag
this.innerHTML = '开始'
}
})
</script>
</body>
2.在页面记载完成后即刻显示时钟的解决办法:
(1)先调用函数
(2)使用事件:load——当浏览器加载页面时触发该事件
<body onload="showTime()"> //表示当前页面加载时就运行showTime函数
3.事件的注册方式
(1)写在页面的标签中
<button onclick="函数名()"></button>
(2)使用addEventlistener注册:
对象名。addEventlistener('事件名',事件处理函数)
(3)使用函数表达式:
let / var 变量名 = function(【参数】){}
注册事件的方式:
对象名。onclick= = function(【参数】){}