欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js实现时钟效果

程序员文章站 2022-03-09 09:08:06
...

js实现时钟效果

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="content">
	<div class="time-wrap">
     <div class="miao"><span></span><span id="hidden"></span></div>
     <div class="fen"><span></span><span id="hidden"></span></div>
     <div class="shi"><span></span><span id="hidden"></span></div>
	</div>
  </div>
<script type="text/javascript">
window.onload=function (){
  var shi = document.querySelector('.shi') 
  var fen = document.querySelector('.fen')
  var miao = document.querySelector('.miao') 
  // miao.style.transform= 'rotate(6deg)' //  6deg:为1分钟
  var nowTime = new Date()
  hours = nowTime.getHours();       //获取当前小时数(0-23)
  minutes = nowTime.getMinutes();     //获取当前分钟数(0-59)
  seconds = nowTime.getSeconds();     //获取当前秒数(0-59)

  setInterval(function(){
  	seconds += 1
  	if(seconds === 60){  
  		minutes = minutes +1 
  		seconds = 1  
   	}
   	if(minutes === 60){
   		hours = hours + 1
   		minutes = 0
   	}
   	if( hours > 24){
   		hours = 1
   	}
   	// 调动指针
   	miao.style.transform= "rotate("+seconds*6+"deg)"
    fen.style.transform= "rotate("+minutes*6+"deg)"
    shi.style.transform= "rotate("+hours*6*5+"deg)"
  	// console.log(hours,minutes,seconds)
  },1000) 
}
</script>
</body>
</html>

css样式 :style.css

*{
	padding: 0;
	margin: 0;
	box-sizing: border-box;
}
.content{
	width: 570px;
	height: 580px;
	margin: 50px auto;
}
.time-wrap{
	width: 570px;
	height: 580px;
	background-image: url('./images/tiem-wrap.png');
	background-size: 100%;
    position: relative;
}
/*秒*/
.miao{
	position: absolute;
	top: 90px;
	left: 280px;
}
.miao > span{
  display: block;
  width: 6px;
  height: 200px;
  border-radius: 50% 50% 0 0;
  background-color: red;
}
/*时*/
.shi{
	position: absolute;
	top: 160px;
	left: 278px;
}
.shi > span{
  display: block;
  width: 10px;
  height: 130px;
  border-radius: 40% 40% 0 0;
  background-color: black;
}
/*时*/
.fen{
	position: absolute;
	top: 130px;
	left: 278px;
}
.fen > span{
  display: block;
  width: 10px;
  height: 160px;
  border-radius: 40% 40% 0 0;
  background-color: black;
}

#hidden{
	visibility: hidden;
}

素材图片
js实现时钟效果