10 472 Скрипты / Time & Clock

Часы

Аналоговые часы на CSS и чистом JS, отображающие текущее время у пользователя

HTML

В контейнере с классом .clock будем с помощью CSS свойств воспроизводить аналоговые часы со стрелкой:
<div class="clock">
  <div class="clock-ui">
    <div class="hand hour"></div>
    <div class="hand min"></div>
    <div class="hand sec"></div>
  </div>
</div> 
<div class="time"></div>
В контейнер .time будем вставлять скриптом текущее время.

CSS

html {
  font-family: Helvetica Neue;
  font-size: 12px;
  background: linear-gradient(#1488cc, #2b32b2);
  color: white;
  box-sizing: border-box;
}

body {
  margin: 0;
  font-size: 2rem;
  display: flex;
  flex: 1;
  min-height: 100vh;
  align-items: center;
}

.clock {
  z-index: 11;
  width: 30rem;
  height: 30rem;
  border: 4px solid white;
  border-radius: 50%;
  margin: 50px auto;
  position: relative;
  padding: 2rem;
  box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.1), inset 0 0 0 3px #EFEFEF, inset 0 0 10px #333, 0 0 10px rgba(0, 0, 0, 0.2);
}

.clock-face {
  position: relative;
  width: 100%;
  height: 100%;
  transform: translateY(-3px);
}

.hand {
  width: 45%;
  height: 6px;
  background: white;
  position: absolute;
  top: 50%;
  transform-origin: 100%;
  transform: rotate(90deg);
  transition: all 0.05s;
  transition-timing-function: cubic-bezier(0.1, 2.7, 0.58, 1);
}
.hand.sec {
  height: 2px;
}
.hand.hour {
  width: 30%;
  left: 21%;
  top: 49%;
}

.time {
  text-align: center;
  position: absolute;
  margin: auto;
  width: 100%;
  font-size: 20vw;
  opacity: .1;
  z-index: 10;
  font-weight: 900;
}

JS

const secondHand = document.querySelector('.sec');
const minsHand = document.querySelector('.min');
const hourHand = document.querySelector('.hour');
const digitalTime = document.querySelector('.time');

function setDate() {
    const now = new Date();
    var seconds = now.getSeconds();
    const secondsDegrees = ((seconds / 60) * 360) + 90;
    secondHand.style.transform = `rotate(${secondsDegrees}deg)`;
    var mins = now.getMinutes();
    const minsDegrees = ((mins / 60) * 360) + ((seconds/60)*6) + 90;
    minsHand.style.transform = `rotate(${minsDegrees}deg)`;
    var hour = now.getHours();
    const hourDegrees = ((hour / 12) * 360) + ((mins/60)*30) + 90;
    hourHand.style.transform = `rotate(${hourDegrees}deg)`;

    digitalTime.innerHTML = parseTime(hour) + ':' + parseTime(mins) + ':' + parseTime(seconds);
}
  
function parseTime(n) {
    if(n < 10) {
        n = '0' + n;
    }
    return n;
}
setInterval(setDate, 1000);
setDate();
Скачать 562Загрузок 2,52 Kb
Демо

Комментарии

  • Facebook
  • Вконтакте

Похожие статьи