效果图
页面html结构
<body>
<div class="clock">
<div class="clock-face">
<div class="hand hour-hand"></div>
<div class="hand min-hand"></div>
<div class="hand second-hand"></div>
</div>
</div>
</body>
css样式
首先设置背景 将整个页面的铺满背景图片
html{
background: #018DED url(https://unsplash.it/1500/1000?image=881&blur=5) ;
background-size: cover;
font-size: 10px;
}
background 是一个简写属性,可以将多个属性写在一起,但是要有顺序
background-size只能跟着position后面出现,所以这里分开写
background-size: cover; 完全覆盖背景区域
``
最外层盒子,将盒子边框设置为圆形,垂直水平居中,再设置盒子阴影
.clock{
position: absolute;
width: 30rem;
height: 30rem;
border: 20px solid white;
border-radius: 50%;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
box-shadow: 0 0 0 4px rgb(0, 0, 0,0.1),
inset 0 0 0 4px rgb(0, 0, 0,0.1),
inset 0 0 10px black,
0 0 10px rgba(0,0,0,0.2) ;
}
将盒子水平居中,垂直居中
这种只适合盒子有宽度
- magin:0 auto
- position + transform
盒子有没有宽高都可以
-
父盒子texi-align+子盒子block-inline
-
flex + justily-content
设置圆心
.clock-face{
position: relative;
width: 100%;
height: 100%;
}
.clock-face::after{
content: "";
width: 1rem;
height: 1rem;
background: #000;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
border-radius: 50%;
box-shadow: 0 0 0 2px rgb(0, 0, 0,0.1);
}
知识点 使用伪元素 ::after 要有content
指针
.hand{
width: 45%;
height: 6px;
margin-left: 5%;
background-color:black;
position:absolute;
top: 50%;
transform: rotate(90deg);
transform-origin: right;
transition: all .5s;
transition-timing-function: cubic-bezier(0,1.74,0.26,0.99);
}
.min-hand{
width: 40%;
/* 宽度减少,就要将指针向右移 */
margin-left: 10%;
}
.hour-hand{
width: 30%;
margin-left: 20%;
}
将旋转的中心改为指针最右边,初始角度指向12点,设置动画延时0,5秒
JavaScript部分
<script>
// 获取时分秒对象
const hourHand = document.querySelector('.hour-hand');
const minHand =document.querySelector('.min-hand');
const secondHand = document.querySelector('.second-hand');
// 获取当前的时分秒
function setDate(){
const now = new Date();
// new Date 不带参数获得的是当前的时间
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
// 分别获取当前的时分秒
// 计算需要的旋转角度
console.log(seconds);
const secondDegree = (seconds/60)*360+90;
//这里加90度是因为后面使用transform会覆盖之前已经添加的transform
const minDegree = ((minutes/60)*360)+((seconds/60)*6)+90;
//除6是化简后的结果
const hourDegree = ((hours/12)*360)+((minutes/60)*30)+90;
//因为转到了12点就会出现指针摇摆
if(secondDegree===90) secondHand.style.transition='all 0s'
else secondHand.style.transition='all .5'
if(minDegree===90) minDegree.style.transition='all 0s'
else minHand.style.transition='all .1s'
//旋转指针
hourHand.style.transform = `rotate(${hourDegree}deg`;
minHand.style.transform = `rotate(${minDegree}deg`;
secondHand.style.transform = `rotate(${secondDegree}deg`;
}
setInterval(setDate,1000)
</script>