我正在尝试设置 javascript 日期计数器的输出样式。我需要能够分别设置日期、小时、分钟和秒的样式。我想将自己的 div 中的每个与它自己的左侧和顶部绝对值右对齐。当我尝试这样做时,计时器不会替换以前的数字,而是添加到它们上,造成一团糟。
这是我尝试单独设置样式的输出代码:
document.getElementById(id).innerHTML = days + 'days ';
document.getElementById(id).innerHTML += hours + 'hrs ';
document.getElementById(id).innerHTML += minutes + 'mins ';
document.getElementById(id).innerHTML += seconds + 'secs';
Here's a fiddle of it working fine but without separate styling
但是,当我尝试将它们放在单独的 div 中时,疯狂的事情发生了,哈哈。计数器不会更新,而只是添加数字。 Here's a fiddle of that
我该怎么做?
最佳答案
当您将 innerHTML
值插入到 div 时,您可以将这些值包装在一个带有类的 span
中。
document.getElementById(id).innerHTML = '<span class="days">' + days + 'days ';
document.getElementById(id).innerHTML += '<span class="hours">' + hours + 'hrs ';
document.getElementById(id).innerHTML += '<span class="minutes">' + minutes + 'mins ';
document.getElementById(id).innerHTML += '<span class="seconds">' + seconds + 'secs';
CountDownTimer('01/01/2016 10:01 AM', 'countdown');
function CountDownTimer(dt, id) {
var end = new Date(dt);
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById(id).innerHTML = '<span class="days">' + days + 'days ';
document.getElementById(id).innerHTML += '<span class="hours">' + hours + 'hrs ';
document.getElementById(id).innerHTML += '<span class="minutes">' + minutes + 'mins ';
document.getElementById(id).innerHTML += '<span class="seconds">' + seconds + 'secs';
}
timer = setInterval(showRemaining, 1000);
}
#countdown {
position: absolute;
z-index: 5;
left: 20px;
top: 20px;
color: #ff0000;
font-family: Helvetica, Arial, sans-serif;
font-size: 32px;
display: inline;
}
.days {
color: lightblue;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12);
padding: 10px;
}
.minutes {
color: tomato;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12);
padding: 10px;
}
.seconds {
color: gray;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12);
padding: 10px;
}
.hours {
color: tomato;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12);
padding: 10px;
}
<div id="countdown">
</div>
关于javascript - 单独设置倒数计时器的 javascript 输出样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33645525/