首先,画钟表页面,主要难点在于钟表那些刻度,可以用一个div包裹一个ul li,用javascrip去设置刻度,用transform:rotate()来做每一个刻度,每一个刻度间角度是6度。
之后是画钟表的时针、分针、秒针,并让这些针转动。
首先在html中敲下如下代码:
接下来css部分:
javascript部分:
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
*{
margin: 0;
padding: 0;
}
.wrap{
width: 200px;
height: 200px;
border: 1px solid;
border-radius: 50%;
position: absolute;
margin: 200px;
}
.wrap ul{
width: 200px;
height: 200px;
list-style: none;
position: relative;
}
/* 每一个刻度长2px,高8px,刻度绕center 100px的点旋转 */
.wrap ul li{
width: 2px;
height: 8px;
position: absolute;
left: 100px;
background-color: black;
-webkit-transform-origin: center 100px;
}
/* 对于数字1~12间的数字,刻度线高度要长一些 */
.wrap ul li:nth-of-type(5n+1){
height: 15px;
}
.icon{
width: 20px;
height: 20px;
border-radius: 50%;
background-color: pink;
position: absolute;
left: 90px;
top: 90px;
}
.hour{
width: 6px;
height: 30px;
background-color: black;
position: absolute;
left: 97px;
top: 70px;
transform-origin: center bottom;
}
.min{
width: 4px;
height: 50px;
background-color:gray;
position: absolute;
left: 100px;
top: 50px;
transform-origin: center bottom;
}
.sec{
width: 2px;
height: 70px;
background-color:red;
position: absolute;
left: 100px;
top: 30px;
transform-origin: center bottom;
}
</style>
<body>
<div class="wrap">
<ul>
<li></li>
</ul>
<!-- 时针、分针、秒针和中间圆点 -->
<div class="hour"></div>
<div class="min"></div>
<div class="sec"></div>
<div class="icon"></div>
</div>
<script>
window.onload = function(){
// 用javascript将每一个刻度做出来
var ulNode = document.querySelector(".wrap ul");
var styleNode = document.createElement("style");
var liHtml = "";
var cssText = "";
// 时针、分针、秒针要转动需要获取的元素
var hourNode = document.querySelector(".wrap .hour");
var minNode = document.querySelector(".wrap .min");
var secNode = document.querySelector(".wrap .sec");
// 将刻度线画在页面上
for(var i=0;i<60;i++){
liHtml+="<li></li>";
cssText+=".wrap ul li:nth-child("+(i+1)+"){transform:rotate("+(6*i)+"deg);}";
}
ulNode.innerHTML = liHtml;
styleNode.innerHTML = cssText;
document.head.appendChild(styleNode);
// 时分秒针的转动
move();
setInterval(move,1000);
function move(){
var date = new Date();
var s = date.getSeconds();
var m = date.getMinutes()+s/60;
var h = date.getHours()+m/60;
hourNode.style.transform = "rotate("+(30*h)+"deg)";
minNode.style.transform = "rotate("+(6*m)+"deg)";
secNode.style.transform = "rotate("+(6*s)+"deg)";
}
}
</script>
</body>
</html>