Heim > Fragen und Antworten > Hauptteil
P粉5503233382023-08-18 14:58:32
您可以使用类和数据属性而不是硬编码的ID。
const countdown = document.querySelector('.countdown'); const numberToImgHtml = (n) => n.toString() .padStart(2, '0') .split('') .map(d => `<img alt="${d}" src="https://okoutdoors.com/img/${d}.png" />`) .join(''); CountDownTimer(countdown, '2023-10-31T00:00:00Z'); function CountDownTimer(el, targetTimestamp) { const endDate = new Date(targetTimestamp); const daysEl = el.querySelector('[data-unit="days"]'); const hoursEl = el.querySelector('[data-unit="hours"]'); const minutesEl = el.querySelector('[data-unit="minutes"]'); const secondsEl = el.querySelector('[data-unit="seconds"]'); const _second = 1000; const _minute = _second * 60; const _hour = _minute * 60; const _day = _hour * 24; let intervalId; function showRemaining() { const delta = endDate - new Date(); if (delta < 0) { clearInterval(intervalId); el.innerHTML = 'EXPIRED!'; return; } const days = Math.floor(delta / _day); const hours = Math.floor((delta % _day) / _hour); const minutes = Math.floor((delta % _hour) / _minute); const seconds = Math.floor((delta % _minute) / _second); daysEl.innerHTML = numberToImgHtml(days); hoursEl.innerHTML = numberToImgHtml(hours); minutesEl.innerHTML = numberToImgHtml(minutes); secondsEl.innerHTML = numberToImgHtml(seconds); } showRemaining(); intervalId = setInterval(showRemaining, 1000); }
html, body { width: 100%; height: 100%; padding: 0; margin: 0 } body { display: flex; flex-direction: column; align-items: center; justify-content: center; background: #000; } .countdown { display: flex; align-items: center; justify-content: center; gap: 2rem; background-image: url(https://okoutdoors.com/img/halloween-before.gif); background-position: top left; background-repeat: no-repeat; background-size: cover; width: 100%; height: 100%; } .unit { display: flex; align-items: center; justify-content: center; }
<div class="countdown"> <div class="unit" data-unit="days"></div> <div class="unit" data-unit="hours"></div> <div class="unit" data-unit="minutes"></div> <div class="unit" data-unit="seconds"></div> </div>