定时器以及小表盘的设计案例
定时器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="screen"> 时间 </div> </body> </html> <script> setInterval(function () { console.log(new Date()) //new Date是当前时间 },1000) //1000代表1000毫秒 //每隔1000ms,让第15行代码console.log(new Date())执行一次 var screen=document.getElementById('screen') function getTime() { screen.innerHTML=new Date().toLocaleTimeString() //只显示时间 } getTime() setInterval(getTime,1000) </script>
小表盘的设计(案例)
步骤:
先将表盘固定在浏览器窗口,再设计三根指针进行固定以及指针固定点。
利用js让指针按照当前时间固定公式围绕表盘旋转。
HTML及CSS代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <style> #clock{ position: relative; width: 225px; height: 225px; margin: 100px auto 0; background: url("img/clock.jpg") no-repeat; background-position: -33px -8px; border-radius: 50%; } #dian{ width: 2px; height: 2px; background: green; position: absolute; left: 112px; top: 112px; } #hourHand{ width: 6px; height: 60px; background: #000; position: absolute; top: 70px; left: 110px; transform-origin: 50% 72%;/*设置hourHand的旋转点*/ } #minuteHand{ width: 4px; height: 80px; background: gray; position: absolute; top: 50px; left: 111px; transform-origin: 50% 79%; } #secondHand{ width: 2px; height: 100px; background: red; position: absolute; top: 40px; left: 112px; transform-origin: 50% 73%; } </style> <body> <div id="clock"> <div id="hourHand"></div> <div id="minuteHand"></div> <div id="secondHand"></div> <div id="dian"></div> </div> </body> </html>
JavaScript代码
<script>
//声明变量,获取元素
var secondHand=document.getElementById('secondHand')
var minuteHand=document.getElementById('minuteHand')
var hourHand=document.getElementById('hourHand')
//设置定时器,让指针自己旋转
setInterval(function () {
//声明变量,方便计算
var time=new Date(),
s=time.getSeconds(),
m=time.getMinutes(),
h=time.getHours()
//以下是要被执行的代码
secondHand.style.transform='rotate('+s*6+'deg)'
minuteHand.style.transform='rotate('+(m+s/60)*6+'deg)'
hourHand.style.transform='rotate('+(h+m/60+s/60/60)*30+'deg)'
},1000)//每1000ms执行以上代码
</script>
浙公网安备 33010602011771号