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

标签 javascript css

只需循环几次,然后为给定的 DIV 显示不同的值,但无法动态设置此 DIV 的样式,知道吗?如何解决?仅供引用,样式部分,我也为这个 DIV 设置了它。但是一旦值改变,样式就消失了(通过样式部分设置的样式不再有效)。 谢谢。

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;");

关于javascript - 如何在 js 过程中操作 div 的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39134776/

相关文章:

jQuery - 我的选择器也在选择另一个 img 元素

javascript - 是否可以制作带有旋转标题单元格的粘性表格标题?

php - 有没有办法让 cURL 等到页面的动态更新完成?

javascript - 想要在nodejs(javascript)中创建一个数组的数组

css - 根据高度缩放 ​​div 宽度

html - CSS按钮:focus pseudo class

html - 无法垂直对齐高度为 auto 的 div 内的 2 个 div 的内容

javascript - 如何使用Jquery循环遍历下面的li元素,并点击所有的li元素

javascript - 隐藏主体溢出时固定位置移动的元素

javascript - axios 如何将 blob 与 arraybuffer 作为响应类型处理?