如何在js过程中操作div的样式



只是去几个循环,然后显示不同的值为一个给定的div,但这个div的样式未能动态设置,任何想法?如何解决这个问题?顺便说一下,样式部分,我也为这个DIV设置了样式。但是,一旦值改变,样式就消失了(通过style部分设置的样式不再有效)。谢谢。

var i = 60;                     //  set your counter to 60
function myLoop () {           //  create a loop function
   setTimeout(function () {    //  call a 3s setTimeout when the loop is called
    if (i < 100) {
        i += 10;                   //  increment the counter by 10
        console.log(i);
// document.getElementById('score').style = "margin: 0; position: absolute; top: 50%; margin-right: -50%; font-size: 216px; transform: translate(-50%, -50%);color: red;";
        document.getElementById('score').innerHTML = i; 
         myLoop();             //  ..  again which will trigger another 
     } 
   }, 3000)
}

element.style指的是样式属性对象(https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style),而不是属性。试着

document.getElementById('score').setAttribute("style", 
"margin: 0; position: absolute; top: 50%; margin-right: -50%; font-size: 216px; transform: translate(-50%, -50%);color: red;");

最新更新