>  기사  >  웹 프론트엔드  >  css3+js는 동적 시계를 그립니다(코드 포함).

css3+js는 동적 시계를 그립니다(코드 포함).

青灯夜游
青灯夜游원래의
2018-09-20 12:52:515913검색

이 장에서는 동적 시계 효과를 얻기 위해 CSS3와 JS를 사용하는 방법을 소개합니다. 도움이 필요한 친구들이 참고할 수 있기를 바랍니다.

먼저 렌더링을 살펴보겠습니다.

css3+js는 동적 시계를 그립니다(코드 포함).

우선 페이지 레이아웃을 생각했는데, 대략 4개의 div 레이어가 필요합니다. 맨 아래 레이어는 다이얼의 배경 이미지이고 나머지 3개의 레이어는 시침, 분침, 초침 레이어입니다.

html 코드는 다음과 같습니다. :

<div class="dial">
</div>
<div class="bigdiv bigdiv1" id="secondHand">
    <div class="secondHand"></div>
</div>
<div class="bigdiv bigdiv2" id="minuteHand">
    <div class="minuteHand"></div>
</div>
<div class="bigdiv bigdiv3" id="hourHand">
    <div class="center"></div>
    <div class="hourHand"></div>
</div>

변수 이름은 무작위로 선택됩니다. class=center인 div는 테이블 중앙에 있는 작은 검은 점입니다.

시간입니다. 바늘은 60*60*60초에 한 번 회전하고 분침은 60*60초에 한 번 회전하며 초침은 60초에 회전합니다. 원이 하나이므로 CSS 코드는 다음과 같습니다.

.dial{
    width:600px;
    height:600px;
    margin:0 auto;
    position: absolute;
    border-radius: 50%;
    overflow: hidden;
    background-color: rgba(153,50,204,0.2);
    background-image: url(img/表盘.jpg);
    background-size: 100% 100%;
}
.bigdiv{
    width:600px;
    height:600px;
    margin:0 auto;
    position: absolute;
    border-radius: 50%;
    overflow: hidden;
}
.bigdiv>div{
    position: absolute;
    left:298px;
    border-radius: 100px;
}
.bigdiv1{
    animation: moves 60s steps(60) infinite;
}
.bigdiv1 .secondHand{
    width:4px;
    height:250px;
    background-color: red;
    top:50px;
    left:298px;
}
.bigdiv2{
    animation: moves 3600s steps(3600) infinite;
}
.bigdiv2 .minuteHand{
    width:6px;
    height:180px;
    background-color: green;
    top:120px;
    left:297px;
}
.bigdiv3{
    animation: moves 216000s steps(216000) infinite;
}
.bigdiv3 .hourHand{
    width:8px;
    height:160px;
    background-color: orange;
    top:140px;
    left:296px;
    border-radius: 100px;
}
.bigdiv .center{
    top:290px;
    left:290px;
    width:20px;
    height:20px;
    background-color: black;
    z-index: 2;
}
@keyframes moves{
    from{ transform: rotateZ(0deg); }
    to{ transform: rotateZ(360deg); }
}

이 단계 이후는 완료되면 렌더링은 다음과 같습니다:

css3+js는 동적 시계를 그립니다(코드 포함).

그런 다음 js를 사용하여 현재 시간을 계산하고

var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();

을 계산합니다. 각 바늘의 현재 회전 각도

var secondAngle = seconds;
var minuteAngle = minutes * 60 + seconds;
var hourAngle = (60/12) * ((hours%12) * 3600 + minuteAngle);

현재 아이디어는 다음과 같습니다. 각 바늘은 자체 시간에 따라 회전합니다. 초기 각도도 알 수 있으며 현재를 표시하는 동적 시계를 형성하는 방법도 있습니다.

초기 아이디어는 이 세 개의 div 레이어를 해당 각도로 회전시킨 다음 다시 시작하는 것이었지만 여전히 고정된 값으로 한 번 회전하기 때문에 생각하지 못했습니다. 시간이 지나면 포인터가 가리키는 방향이 벗어나게 됩니다.

지금 필요한 것은 들어오는 페이지의 첫 번째 원이 고정된 각도로 회전하고 나머지는 원래 고정된 시간으로 회전하는 것입니다.# 🎜 🎜#

css3에는 animation-delay 속성이 있는데, 이는 애니메이션 지연을 의미합니다. 음수는 일찍 시작한다는 의미입니다. 예를 들어 -5s는 애니메이션이 5초에 시작된다는 의미입니다.

#🎜 🎜# 이 포인터가 해당 각도를 미리 시작하도록 하는 데 사용할 수 있습니다.

js 코드는 다음과 같습니다.

hourHand.style.cssText = "animation-delay: -"+ hourAngle +"s";
minuteHand.style.cssText = "animation-delay: -"+ minuteAngle +"s";
secondHand.style.cssText = "animation-delay: -"+ secondAngle +"s";

마지막으로 동적 시간을 추가했습니다. 시계 위에 표시된 것은

의 전체 코드입니다.

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			body,
			html {
				margin: 0;
			}
			
			.location {
				position: relative;
				width: 600px;
				height: 600px;
				left: calc(50% - 300px);
			}
			
			.dial {
				width: 600px;
				height: 600px;
				margin: 0 auto;
				position: absolute;
				border-radius: 50%;
				overflow: hidden;
				background-color: rgba(153, 50, 204, 0.2);
				background-image: url(img/表盘.jpg);
				background-size: 100% 100%;
			}
			
			.bigdiv {
				width: 600px;
				height: 600px;
				margin: 0 auto;
				position: absolute;
				border-radius: 50%;
				overflow: hidden;
			}
			
			.bigdiv>div {
				position: absolute;
				left: 298px;
				border-radius: 100px;
			}
			
			.bigdiv1 {
				animation: moves 60s steps(60) infinite;
			}
			
			.bigdiv1 .secondHand {
				width: 4px;
				height: 250px;
				background-color: red;
				top: 50px;
				left: 298px;
			}
			
			.bigdiv2 {
				animation: moves 3600s steps(3600) infinite;
			}
			
			.bigdiv2 .minuteHand {
				width: 6px;
				height: 180px;
				background-color: green;
				top: 120px;
				left: 297px;
			}
			
			.bigdiv3 {
				animation: moves 216000s steps(216000) infinite;
			}
			
			.bigdiv3 .hourHand {
				width: 8px;
				height: 160px;
				background-color: orange;
				top: 140px;
				left: 296px;
				border-radius: 100px;
			}
			
			.bigdiv .center {
				top: 290px;
				left: 290px;
				width: 20px;
				height: 20px;
				background-color: black;
				z-index: 2;
			}
			
			@keyframes moves {
				from {
					transform: rotateZ(0deg);
				}
				to {
					transform: rotateZ(360deg);
				}
			}
			
			#dateshow {
				text-align: center;
			}
		</style>

	</head>

	<body>
		<h1 id="dateshow"></h1>
		<div class="location">
			<div class="dial"></div>
			<div class="bigdiv bigdiv1" id="secondHand">
				<div class="secondHand"></div>
			</div>
			<div class="bigdiv bigdiv2" id="minuteHand">
				<div class="minuteHand"></div>
			</div>
			<div class="bigdiv bigdiv3" id="hourHand">
				<div class="center"></div>
				<div class="hourHand"></div>
			</div>
		</div>
		<script>
			var dateshow = document.getElementById("dateshow");
			var clock = {
				weeks: ["一", "二", "三", "四", "五", "六", "日"],
				getDate: function() {
					date = new Date();
					year = date.getFullYear();
					month = date.getMonth() + 1;
					day = date.getDate();
					hours = date.getHours();
					minutes = date.getMinutes();
					seconds = date.getSeconds();
					week = date.getDay(); // 星期
					dateText = year + "年" + month + "月" + clock.format(day) + "日 星期" + clock.formatnum(week) + " " +
						clock.format(hours) + ":" + clock.format(minutes) + ":" + clock.format(seconds);
					return dateText;
				},
				format: function(data) {
					if(data.toString().length == 1) {
						data = "0" + data;
					};
					return data;
				},
				formatnum: function(num) {
					return clock.weeks[num - 1];
				},
				showdate: function() {
					dateshow.innerText = clock.getDate();
				},
				go: function() {
					var secondHand = document.getElementById("secondHand");
					var minuteHand = document.getElementById("minuteHand");
					var hourHand = document.getElementById("hourHand");
					date = new Date();
					hours = date.getHours();
					minutes = date.getMinutes();
					seconds = date.getSeconds();
					var secondAngle = seconds;
					var minuteAngle = minutes * 60 + seconds;
					var hourAngle = (60 / 12) * ((hours % 12) * 3600 + minuteAngle);
					hourHand.style.cssText = "animation-delay: -" + hourAngle + "s";
					minuteHand.style.cssText = "animation-delay: -" + minuteAngle + "s";
					secondHand.style.cssText = "animation-delay: -" + secondAngle + "s";
				}

			}
			clock.go();
			clock.showdate();
			setInterval("clock.showdate()", 1000);
		</script>
	</body>

</html>

위 내용은 css3+js는 동적 시계를 그립니다(코드 포함).의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.