Для акций или отдельных дать периодически может возникать необходимость реализовать обратный отсчет. Как это сделать узнайте в этой статье.
HTML
<section>
<div class="coming-soon">
<div class="time-countdown">
<ul>
<li class="count-bg-one radius"><span id="days">{{day}}</span>Дни</li>
<li class="count-bg-two radius"><span id="hours">{{hours}}</span>Часы</li>
<li class="count-bg-three radius"><span id="minutes">{{minutes}}</span>Минуты</li>
<li class="count-bg-four radius"><span id="seconds">{{seconds}}</span>Секунды</li>
</ul>
</div>
</div>
</section>
Code language: HTML, XML (xml)
CSS
section {
width: 100%;
height: 100%;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
ul {
display: flex;
justify-content: center;
}
.coming-soon {
width: 100%;
}
.time-countdown ul {
margin: 36px auto;
}
.time-countdown ul li.count-bg-one {
background: #468dbc;
}
.time-countdown ul li.count-bg-two {
background: #ef9024;
}
.time-countdown ul li.count-bg-three {
background: #ee337f;
}
.time-countdown ul li.count-bg-four {
background: #1fb1f4;
margin-right: 0;
}
.time-countdown ul li {
width: 12%;
margin-right: 4%;
text-align: center;
display: inline-block;
padding: 24px 20px;
color: #fff;
}
.radius {
border-radius: 5px;
}
.time-countdown ul li span {
color: #FFF;
font-family: 'Poppins', sans-serif;
font-size: 50px;
line-height: 60px;
font-weight: 700;
display: block;
}
Code language: CSS (css)
TS
import { Component, OnInit } from '@angular/core';
import { timer } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
_second = 1000;
_minute = this._second * 60;
_hour = this._minute * 60;
_day = this._hour * 24;
end: any;
now: any;
day: any;
hours: any;
minutes: any;
seconds: any;
source = timer(0, 1000);
clock: any;
constructor(){}
ngOnInit(){
this.clock = this.source.subscribe(t => {
this.now = new Date();
this.end = new Date('01/01/' + (this.now.getFullYear() + 1) +' 00:00');
this.showDate();
});
}
showDate(){
let distance = this.end - this.now;
this.day = Math.floor(distance / this._day);
this.hours = Math.floor((distance % this._day) / this._hour);
this.minutes = Math.floor((distance % this._hour) / this._minute);
this.seconds = Math.floor((distance % this._minute) / this._second);
}
}
Code language: JavaScript (javascript)
Пояснение работы обратного отсчета
Осталось добавить совсем немного, мы видим, что в ts мы добавляем библиотеку таймера rxjs, это нужно для того, чтобы установить часы с обратным отсчетом.
Мы делаем небольшое преобразование времени, объявляя секунды в миллисекундах и умножая их до получения дней.
_second = 1000;
_minute = this._second * 60;
_hour = this._minute * 60;
_day = this._hour * 24;
Самая важная часть:
let distance = this.end – this.now;
С помощью этого мы выполняем вычитание дат, чтобы узнать, сколько дней осталось до определенного события.