如何设置这个javascript倒计时器的样式

时间:2015-03-18 21:17:59

标签: javascript html timer

我一直在关注如何创建javascript倒计时器的教程。我想在<h1>标签中显示每个标签,以便我可以用CSS设置它,但是到目前为止我所有的尝试都失败了,老实说我不知道​​如何去做。任何帮助表示赞赏

HTML

<span id="countdown"></span> 

的Javascript

// set the date we're counting down to
var target_date = new Date("Aug 15, 2019").getTime();

// variables for time units
var days, hours, minutes, seconds;

// get tag element
var countdown = document.getElementById("countdown");

// update the tag with id "countdown" every 1 second
setInterval(function () {

    // find the amount of "seconds" between now and target
    var current_date = new Date().getTime();
    var seconds_left = (target_date - current_date) / 1000;

    // do some time calculations
    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;

    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;

    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);

    // format countdown string + set tag value
    countdown.innerHTML = days + "d, " + hours + "h, "
    + minutes + "m, " + seconds + "s";  

}, 1000);

2 个答案:

答案 0 :(得分:1)

无需使用标签。另外调整范围的样式。

span#countdown {
    font-size: 48px;
    border: 3px solid black;
    padding: 5px;
    background-color: #ffe;
}

请参阅http://jsfiddle.net/8mw6beqh/

答案 1 :(得分:1)

有趣的是,我正在做同样的事情。我使用了第一种观察方法,但无法针对每种方法进行定位。这是我完成的codepen

所以我为不同的元素创建了单独的变量。

var daysTimer = document.getElementById("dayTimer");
var hourTimer = document.getElementById("hourTimer");
var minuteTimer = document.getElementById("minuteTimer");
var secondTimer = document.getElementById("secondTimer");

并确保单独运行

// format countdown string + set tag value
dayTimer.innerHTML = days;
hourTimer.innerHTML = hours;
minuteTimer.innerHTML = minutes;
secondTimer.innerHTML = seconds;

我在无序列表中使用它们,如下所示:

<div id="clock">
  <ul id=time>
    <li id="dayTimer"></li>
    <li id="hourTimer"></li>
    <li id="minuteTimer"></li>
    <li id="secondTimer"></li>
  </ul>
</div>