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



我已经简单地完成了我的倒数计时器,但是现在我想在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);
.countdown
{
margin:0 auto;
font-weight: 100;
font-size:3em;color: white;
width: 100%;
text-align: center;
background-image:blue;
}
<div class="countdown" id="demo"></div>

您的小提琴链接是空的,但是从问题的标题中,您想将CSS类添加到纯JavaScript中使用getElementById()的元素中。如果是这样,这里有一个选择:

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

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

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

最新更新