如何使用document.getElementById在倒数计时器中为输出元素添加类(样式)?

时间:2017-03-03 15:25:41

标签: javascript html css

我已经完成了我的倒计时器简单但现在我想在Javascript中为它添加样式。我怎么能这样做?输出值是否可能不同?如果是,怎么样?

这是来源



var countDownDate = new Date("Jan 5, 2018 15:37:25").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();
    
    // Find the distance between now an the count down date
    var distance = countDownDate - now;
    
    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
    // Output the result in an element with id="demo"
    document.getElementById("demo").innerHTML = days  + "d " + hours + "h "
    + minutes + "m " + seconds + "s ";
    
    // If the count down is over, write some text 
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
    }
}, 1000);
&#13;
.countdown
{
margin:0 auto;
font-weight: 100;
font-size:3em;color: white;
width: 100%;
text-align: center;
background-image:blue;
}
&#13;
<div class="countdown" id="demo"></div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

你的小提琴链接是空的,但是从我想问的标题中,你想要在纯javascript中使用getElementById()的元素添加一个CSS类。如果是这样,这里有一个选项:

document.getElementById('your_element_id').classList.add('class_to_add');

答案 1 :(得分:0)

这是一个页面,解释了如何通过更改其类或通过操纵其样式来设置元素的样式。

https://www.w3schools.com/jsref/met_element_setattribute.asp