Как сделать таймер обратного отсчета
- Особенности работы скрипта
- Пошаговая инструкция по добавлению блока таймера
- Как добавить таймер с разным временем отсчета на страницы
Блок таймера обратного отсчета позволяет показывать оставшееся время до события, например, до акции, распродажи или вебинара. Это стимулирует посетителей к действиям и помогает подчеркнуть срочность предложения.
Особенности работы скрипта
- Фиксированное время отсчета: таймер начинает отсчет от заданной даты и времени, что позволяет синхронизировать его с вашим событием.
- Постоянство таймера: дата окончания сохраняется в localStorage, поэтому таймер не сбивается при обновлении страницы.
- Автоматическое скрытие: если дата прошла, блок с таймером скрывается автоматически.
- Визуальное оформление: таймер выглядит стильно и привлекательно, благодаря возможности разделять цифры на отдельные элементы.
Пошаговая инструкция по добавлению блока таймера
Пример №1: Большой блок с таймером
Этот блок помогает привлечь внимание пользователей и побуждает их действовать быстрее.
Демонстрация работы таймера №1
1. Создание глобального блока
В панели управления сайта откройте: «Дизайн» → «Управление дизайном» → «Редактирование шаблонов» → «Глобальные блоки». Создайте новый глобальный блок и вставьте в него следующий код:
<div class="promo-container"> <div class="promo-block"> <div class="promo-wrapper"> <div class="promo-banner"> <img class="promo-img" src="https://timer.ucoz.net/img/banner.png" alt="banner"> <div class="promo-timer"> <div class="promo-text"> <h2>Распродажа коллекции "Элегантность"</h2> <p>Только до 31.08.2024 у вас есть шанс приобрести наши премиум духи по невероятным ценам.</p> </div> <div id="countdown-timer"> <div class="time-unit"> <div class="time-digits" id="days"></div> <div>Дней</div> </div> <div class="time-unit"> <div class="time-digits" id="hours"></div> <div>Часов</div> </div> <div class="time-unit"> <div class="time-digits" id="minutes"></div> <div>Минут</div> </div> <div class="time-unit"> <div class="time-digits" id="seconds"></div> <div>Секунд</div> </div> </div> <a href="#" class="button-link promo-btn" style="display:flex; margin: 0 auto; justify-content: center; width: 60%; margin-top: 10px;">Перейти в каталог</a> </div> </div> </div> </div> </div>
2. Добавление стилей
Скопируйте стили и вставьте их в шаблон «Таблица стилей (CSS)»:
.promo-container {
max-width: 1240px;
padding: 0;
margin: 0 auto;
width: 100%;
}
.promo-block {
flex-shrink: 0;
width: 100%;
height: 100%;
position: relative;
display: block;
margin-top: 16px;
}
.promo-wrapper {
position: relative;
width: 100%;
height: 100%;
z-index: 1;
display: flex;
box-sizing: content-box;
}
.promo-banner {
flex-shrink: 0;
width: 100%;
height: 100%;
position: relative;
transition-property: transform;
display: block;
}
.promo-img {
border-radius: 16px;
display: block;
height: 100%;
inset: 0;
object-fit: cover;
position: absolute;
width: 100%;
}
.promo-text {
text-align: center;
}
.promo-text h2 {
margin-bottom: 5px;
font-size: 24px;
}
.promo-timer {
background-color: var(--tpl-dark-100);
border-radius: 12px;
margin: 16px;
max-width: 420px;
padding: 0px 20px 20px 20px;
position: relative;
float: right;
}
#countdown-timer {
display: flex;
justify-content: center;
margin-top: 10px;
}
.time-digits {
display: flex;
gap: 5px; /* Отступ между цифрами */
}
.time-digit {
font-weight: bold;
background-color: #507fff;
color: white;
padding: 5px 10px;
border-radius: 5px;
width: 40px;
display: flex;
justify-content: center;
align-items: center;
}
.time-unit {
display: flex;
flex-direction: column;
align-items: center;
margin: 0 5px;
}
.time-unit span {
font-size: 30px;
font-weight: bold;
background-color: #3367f4;
color: white;
padding: 5px 10px;
border-radius: 5px;
}
.time-unit div {
font-size: 14px;
margin-top: 5px;
font-weight: bold;
}
@media (max-width: 768px) {
.promo-text h2 {
font-size: 18px;
}
.time-digit {
width: 32px;
padding: 3px 6px;
}
.promo-timer {
padding: 0 10px 20px 10px;
}
}
3. Настройка скрипта
Вставьте скрипт для управления таймером в глобальный блок «Нижняя часть сайта»:
<script>
document.addEventListener("DOMContentLoaded", function () {
const promoEndDateKey = 'promoEndDate';
const fixedStartDateStr = '2024-08-31T16:00:00';
const fixedStartDate = new Date(fixedStartDateStr);
const currentDate = new Date();
if (isNaN(fixedStartDate.getTime()) || fixedStartDate <= currentDate) {
document.querySelector(".promo-container").classList.add("u-hidden");
return;
}
let promoEndDate = localStorage.getItem(promoEndDateKey);
if (!promoEndDate) {
const endDate = fixedStartDate.getTime();
localStorage.setItem(promoEndDateKey, endDate);
promoEndDate = endDate;
} else {
promoEndDate = parseInt(promoEndDate, 10);
if (currentDate.getTime() > promoEndDate) {
localStorage.removeItem(promoEndDateKey);
document.querySelector(".promo-container").classList.add("u-hidden");
return;
}
}
function updateTimer() {
const now = new Date().getTime();
const distance = promoEndDate - now;
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
const formatTime = (value) => String(value).padStart(2, '0');
document.getElementById("days").innerHTML = splitDigits(formatTime(days));
document.getElementById("hours").innerHTML = splitDigits(formatTime(hours));
document.getElementById("minutes").innerHTML = splitDigits(formatTime(minutes));
document.getElementById("seconds").innerHTML = splitDigits(formatTime(seconds));
function splitDigits(number) {
return number.split('').map(digit => `${digit}`).join('');
}
if (distance < 0) {
clearInterval(timerInterval);
document.querySelector(".promo-container").classList.add("u-hidden");
localStorage.removeItem(promoEndDateKey);
}
}
updateTimer();
const timerInterval = setInterval(updateTimer, 1000);
});
</script>
2024-08-31T16:00:00.
const fixedStartDateStr = '2024-08-31T16:00:00';
Пример №2: Таймер под шапкой сайта
Этот блок используется для уведомления пользователей о важных акциях и событиях. Он располагается в верхней части сайта и сразу привлекает внимание посетителей. При необходимости пользователь может закрыть блок, чтобы он не мешал дальнейшему просмотру.
Демонстрация работы таймера №2
1. Создание глобального блока
Создайте новый глобальный блок в панели «Управление дизайном» и добавьте в него следующий код:
<div class="promo-container"> <div class="promo-wrapper"> <div class="promo-banner"> <img alt="banner" class="promo-img" src="https://timer.ucoz.net/img/banner.png" /> <div class="promo-content"> <div class="close-btn" onclick="closePopup()"> <svg class="icon icon-tabler icons-tabler-outline icon-tabler-x" fill="none" height="20" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewBox="0 0 24 24" width="20" xmlns="http://www.w3.org/2000/svg"> <path d="M0 0h24v24H0z" fill="none" stroke="none"></path> <path d="M18 6l-12 12"></path> <path d="M6 6l12 12"></path> </svg> </div> <div class="promo-text"> <strong style="font-size: 18px;">Сезонная распродажа</strong> <p style="text-align: center;">скидки до 50% на духи</p> </div> <div class="promo-timer"> <div id="countdown-timer"> <div class="time-unit"> <div class="time-digits" id="days"> </div> <div>Дней</div> </div> <div class="time-unit"> <div class="time-digits" id="hours"> </div> <div>Часов</div> </div> <div class="time-unit"> <div class="time-digits" id="minutes"> </div> <div>Минут</div> </div> <div class="time-unit"> <div class="time-digits" id="seconds"> </div> <div>Секунд</div> </div> </div> </div> <div class="promo-button"> <a class="button-link promo-btn" href="#">Перейти в каталог</a> </div> </div> </div> </div> </div>
2. Добавление стилей
Скопируйте стили и вставьте их в шаблон «Таблица стилей (CSS)»:
.promo-container {
padding: 0;
margin: 0 auto;
width: 100%;
}
.promo-wrapper {
position: relative;
width: 100%;
height: 100%;
z-index: 1;
display: flex;
transition-property: transform;
transition-timing-function: var(--swiper-wrapper-transition-timing-function, initial);
box-sizing: content-box;
}
.promo-banner {
flex-shrink: 0;
width: 100%;
height: 100%;
position: relative;
display: block;
padding: 10px;
}
.promo-img {
background-color: var(--tpl-dark-100, gray);
display: block;
height: 100%;
inset: 0;
object-fit: cover;
position: absolute;
width: 100%;
}
.promo-content {
display: flex;
justify-content: center;
align-items: center;
background-color: var(--tpl-dark-100);
border-radius: 12px;
padding: 10px;
position: relative;
margin: 0 auto;
gap: 30px;
max-width: 800px;
}
#countdown-timer {
display: flex;
justify-content: center;
}
.time-digits {
display: flex;
gap: 5px;
}
.time-digit {
font-size: 24px;
font-weight: bold;
background-color: #507fff;
color: white;
padding: 5px 10px;
border-radius: 5px;
width: 30px;
display: flex;
justify-content: center;
align-items: center;
}
.time-unit {
display: flex;
flex-direction: column;
align-items: center;
margin: 0 5px;
}
.time-unit span {
font-size: 16px;
font-weight: bold;
background-color: #3367f4;
color: white;
padding: 5px 10px;
border-radius: 5px;
}
.time-unit div {
font-size: 12px;
margin-top: 5px;
font-weight: bold;
}
.close-btn {
position: absolute;
top: -4px;
right: -4px;
cursor: pointer;
z-index: 1000;
}
.close-btn svg {
width: 24px;
height: 24px;
border-radius: 50%;
background-color: var(--tpl-dark-200);
padding: 4px;
}
.close-btn svg:hover {
background-color: var(--tpl-dark-300);
}
@media (max-width: 768px) {
.promo-content {
flex-direction: column;
gap: 10px;
}
.time-digit {
font-size: 18px;
width: 30px;
padding: 3px 6px;
}
h2 {
font-size: 24px;
}
}
3. Настройка скрипта
Добавьте скрипт для работы таймера и функционала закрытия блока в глобальный блок «Нижняя часть сайта»:
<script>
document.addEventListener("DOMContentLoaded", function () {
const promoEndDateKey = 'promoEndDate';
const fixedStartDateStr = '2024-08-31T16:00:00';
const fixedStartDate = new Date(fixedStartDateStr);
const currentDate = new Date();
if (isNaN(fixedStartDate.getTime()) || fixedStartDate <= currentDate) {
document.querySelector(".promo-container").classList.add("u-hidden");
return;
}
let promoEndDate = localStorage.getItem(promoEndDateKey);
if (!promoEndDate) {
const endDate = fixedStartDate.getTime();
localStorage.setItem(promoEndDateKey, endDate);
promoEndDate = endDate;
} else {
promoEndDate = parseInt(promoEndDate, 10);
if (currentDate.getTime() > promoEndDate) {
localStorage.removeItem(promoEndDateKey);
document.querySelector(".promo-container").classList.add("u-hidden");
return;
}
}
// Проверка, закрыт ли баннер
function isPromoClosed() {
return document.cookie.split(';').some(item => item.trim().startsWith('promoClosed='));
}
if (isPromoClosed()) {
document.querySelector(".promo-container").classList.add("u-hidden");
return;
}
function updateTimer() {
const now = new Date().getTime();
const distance = promoEndDate - now;
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
const formatTime = (value) => String(value).padStart(2, '0');
document.getElementById("days").innerHTML = splitDigits(formatTime(days));
document.getElementById("hours").innerHTML = splitDigits(formatTime(hours));
document.getElementById("minutes").innerHTML = splitDigits(formatTime(minutes));
document.getElementById("seconds").innerHTML = splitDigits(formatTime(seconds));
function splitDigits(number) {
return number.split('').map(digit => `${digit}`).join('');
}
if (distance < 0) {
clearInterval(timerInterval);
document.querySelector(".promo-container").classList.add("u-hidden");
localStorage.removeItem(promoEndDateKey);
}
}
updateTimer();
const timerInterval = setInterval(updateTimer, 1000);
window.closePopup = function() {
document.querySelector(".promo-container").classList.add("u-hidden");
document.cookie = "promoClosed=true; max-age=" + 24 * 60 * 60;
};
});
</script>
2024-08-31T16:00:00, иначе блок не будет отображаться.
const fixedStartDateStr = '2024-08-31T16:00:00';
Как добавить таймер с разным временем отсчета на страницы
Чтобы добавить таймеры с индивидуальным временем отсчета для каждой страницы, выполните следующие шаги:
1. Включите дополнительное поле в модуле для хранения даты и времени таймера (в формате ISO 8601). Вставьте глобальный блок с кодом таймера в шаблон «Страница материала и комментариев к нему».
2. Добавьте изменённый скрипт перед закрывающим тегом </body> в шаблон:
<script>
document.addEventListener("DOMContentLoaded", function () {
// Используем значение из дополнительного поля $OTHER1$
const fixedStartDateStr = '$OTHER1$';
const fixedStartDate = new Date(fixedStartDateStr);
const currentDate = new Date();
if (isNaN(fixedStartDate.getTime()) || fixedStartDate <= currentDate) {
document.querySelector(".promo-container").classList.add("u-hidden");
return;
}
const promoEndDate = fixedStartDate.getTime();
function updateTimer() {
const now = new Date().getTime();
const distance = promoEndDate - now;
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
const formatTime = (value) => String(value).padStart(2, '0');
document.getElementById("days").innerHTML = splitDigits(formatTime(days));
document.getElementById("hours").innerHTML = splitDigits(formatTime(hours));
document.getElementById("minutes").innerHTML = splitDigits(formatTime(minutes));
document.getElementById("seconds").innerHTML = splitDigits(formatTime(seconds));
function splitDigits(number) {
return number.split('').map(digit => `${digit}`).join('');
}
if (distance < 0) {
clearInterval(timerInterval);
document.querySelector(".promo-container").classList.add("u-hidden");
}
}
updateTimer();
const timerInterval = setInterval(updateTimer, 1000);
window.closePopup = function() {
document.querySelector(".promo-container").classList.add("u-hidden");
};
});
</script>
3. При добавлении материала укажите дату и время для таймера в дополнительном поле. Например: 2024-08-31T16:00:00
Теперь каждый таймер будет отображать индивидуальное время отсчета, указанное для конкретной страницы!

