只需循环几次,然后为给定的 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/